$a ="SCNSC: SME@companay.isa.come";
$b ="alerts: nek";
$c ="daily-report: tasd,dfgd,fgdfg,dfgdf,sdf@dfs.com";
print "matched" if ($a =~ /\w+:\s*\w+@\w+\.\w+/ );
print "matched" if ($b =~ /\w+:\s*\w+[,\w+]{0,}/ );
print "matched" if ($c =~ /\w+:\s*\w+[,\w+]{0,}/ );
Run Code Online (Sandbox Code Playgroud)
它没有显示匹配
该-W警告选项是你的朋友:
$ perl -W sample .pl
Possible unintended interpolation of @companay in string at junk.pl line 1.
Possible unintended interpolation of @dfs in string at junk.pl line 3.
Name "main::companay" used only once: possible typo at junk.pl line 1.
Name "main::dfs" used only once: possible typo at junk.pl line 3.
Run Code Online (Sandbox Code Playgroud)
所以$a并且$c不包含文字@companay,@dfs它们包含在其位置插值的空(未定义)数组.表达式{0,}相当于*(意味着零或更多)所以让我们清理它并且Perl已经有太多标点符号,所以让我们删除不需要的括号.这给了我们Perl没有警告我们的唯一匹配:
print "matched" if $b =~ /\w+:\s*\w+[,\w+]*/ ;
Run Code Online (Sandbox Code Playgroud)
这很好,除了你可能意味着使用分组括号作为正则表达式的最后一部分,而不是"包含, \w和的字符类的零或更多次出现+.修复所有这些产生:
$a ='SCNSC: SME@companay.isa.come';
$b ='alerts: nek';
$c ='daily-report: tasd,dfgd,fgdfg,dfgdf,sdf@dfs.com';
print "matched\n" if $a =~ /\w+:\s*\w+@\w+\.\w+/ ;
print "matched\n" if $b =~ /\w+:\s*\w+(,\w+)*/ ;
print "matched\n" if $c =~ /\w+:\s*\w+(,\w+)*/ ;
Run Code Online (Sandbox Code Playgroud)
哪个匹配所有字符串.请注意,\w不包括角色,@因此它们匹配,但可能不是您想要的.