How to check for strings between certain strings i

2019-03-04 03:32发布

String:

name@gmail.com

Checking for:

@
.com

My code

if [[ $word =~ "@" ]] 
then 
    if [[ $word =~ ".com" || $word =~ ".ca"  ]]

My problem

name@.com

The above example gets passed, which is not what I want. How do I check for characters (1 or more) between "@" and ".com"?

标签: shell unix
3条回答
冷血范
2楼-- · 2019-03-04 03:49

You can use a very very basic regex:

[[ $var =~ ^[a-z]+@[a-z]+\.[a-z]+$ ]]

It looks for a string being exactly like this:

at least one a-z char
@
at least one a-z char
.
at least one a-z char

It can get as complicated as you want, see for example Email check regular expression with bash script.

See in action

$ var="a@b.com"

$ [[ $var =~ ^[a-z]+@[a-z]+\.[a-z]+$ ]] && echo "kind of valid email"
kind of valid email

$ var="a@.com"
$ [[ $var =~ ^[a-z]+@[a-z]+\.[a-z]+$ ]] && echo "kind of valid email"
$
查看更多
来,给爷笑一个
3楼-- · 2019-03-04 03:59

why not go for other tools like perl:

> echo "x@gmail.com" | perl -lne 'print $1 if(/@(.*?)\.com/)'
gmail
查看更多
你好瞎i
4楼-- · 2019-03-04 03:59

The glob pattern would be: [[ $word == ?*@?*.@(com|ca) ]]

? matches any single character and * matches zero or more characters

@(p1|p2|p3|...) is an extended globbing pattern that matches one of the given patterns. This requires:
shopt -s extglob

testing:

$ for word in @.com @a.ca a@.com a@b.ca a@b.org; do
    echo -ne "$word\t"
    [[ $word == ?*@?*.@(com|ca) ]] && echo matches || echo does not match
done
@.com   does not match
@a.ca   does not match
a@.com  does not match
a@b.ca  matches
a@b.org does not match
查看更多
登录 后发表回答