字符串:
name@gmail.com
检查:
@
.com
我的代码
if [[ $word =~ "@" ]]
then
if [[ $word =~ ".com" || $word =~ ".ca" ]]
我的问题
name@.com
上面的例子被传递,这不是我想要的。如何检查“@”和“.com”之间的字符(1或更多)?
答案 0 :(得分:3)
您可以使用非常基本的正则表达式:
[[ $var =~ ^[a-z]+@[a-z]+\.[a-z]+$ ]]
它查找的字符串完全如下:
at least one a-z char
@
at least one a-z char
.
at least one a-z char
它可以变得如你所想的那样复杂,例如参见Email check regular expression with bash script。
$ 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"
$
答案 1 :(得分:1)
为什么不去寻找其他工具,比如perl:
> echo "x@gmail.com" | perl -lne 'print $1 if(/@(.*?)\.com/)'
gmail
答案 2 :(得分:1)
glob模式是:[[ $word == ?*@?*.@(com|ca) ]]
?
匹配任何单个字符,*
匹配零个或多个字符
@(p1|p2|p3|...)
是一个匹配给定模式之一的extended globbing pattern。这要求:
shopt -s extglob
测试:
$ 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