为什么这个正则表达式没有正确地抓住时期?

时间:2015-08-24 02:51:55

标签: regex bash shell match no-match

我正在努力学习有关shell脚本的更多信息。所以,我有一些带有电子邮件的文件,其中spamassassin写入目录,我想我会尝试在它们上进行一些正则表达式匹配。因此,我选择需要不同匹配的文件,然后尝试对它们进行排序。

我写了这个剧本:

#!/usr/local/bin/bash
#
regex='(\.)?'
files="/var/spool/spam/testing/out.*"
for i in $files; do
domain=`cat $i | grep -i "Message-ID: <" | cut -d'@' -f2 | cut -d'>' -f1 | cut -d' ' -f1`
echo "Domain is $domain"
echo "We're starting the if loop"
if [ -z "$domain" ];
then
echo "Domain is empty"
echo $i
#rm $i
elif ! [[ "$domain" =~ $regex ]];
then
echo "There are no periods in the domainname $domain"
elif [[ $domain =~ $regex ]];
then
echo "There are periods in the domainname $domain"
fi
done

我想要完成的是将Message-ID的域部分分开:然后确定该域是什么。有些Message-ID根本没有域名。有些人有虚假的域名。有些人拥有这样的域名:yahoo.co.uk。

每封邮件都有两个Message-ID:条目,因此域名最终会出现两次。

当我在两个文件上运行此脚本时,这是我得到的结果:

# bash /usr/local/bin/rm-bounces.sh 
Domain is xbfoqrka
xbfoqrka
We're starting the if loop
There are periods in the domainname xbfoqrka
xbfoqrka
Domain is SKY-20150201SFT.com
SKY-20150201SFT.com
We're starting the if loop
There are periods in the domainname SKY-20150201SFT.com
SKY-20150201SFT.com

我不明白为什么xbfoqrka匹配应该在域名中找到句点的正则表达式,但与在域名中查找NO句点的正则表达式不匹配。我正在逃避这个时期,所以它应该是完全匹配的,并且在xbfoqrka xbfoqrka中没有句号。

1 个答案:

答案 0 :(得分:1)

?符号表示零或一。因此正则表达式在文本中寻找至少为零或一.。由于.中没有xbfoqrka,因此正则表达式会找到匹配项(对于零)。

请注意,正则表达式将为任意数量的.返回true - 零,一,三,100等。这是因为一个包含100个点的字符串至少有一个零点或一个点。