Perl正则表达式:at @符号是否需要被转义?
我无法确定为什么我的正则表达式失败。这里是我的代码:Perl正则表达式:at @符号是否需要被转义?
my $email = "[email protected]";
my ($found) = $email =~ /([email protected]\.com)/;
print "Found: $found";
这将导致输出:
C:\scripts\perl\sandbox>regex.pl
Found: rise.com
如果我逃避@符号,然后我得到任何输出:
my $email = "[email protected]";
my ($found) = $email =~ /(rise\@dawn\.com)/;
print "Found: $found";
C:\scripts\perl\sandbox>regex.pl
Found:
可能有人请启发我对我的错误。
始终use strict; use warnings;
在脚本的顶部!
它会警告你有一个未声明的全局变量@dawn
。阵列可插值到双引号字符串一样,所以你需要
my $email = "rise\@dawn.com";
my ($found) = $email =~ /(rise\@dawn\.com)/;
print "Found: $found";
当我从文件中读取文本时,是否被视为“单引号”字符串? –
是的。除非您明确要求数据,否则不会将数据评估为Perl代码。否则,Perl会有可怕的安全问题。插值规则仅适用于脚本中的字符串文字。 – amon
有道理。谢谢:) –
在Perl中的双引号字符串或正则表达式,一个@
后跟一个字被当作一个数组,其值是名称在空间上插入到该位置的字符串或正则表达式中,类似于处理"scalar $variables in strings"
。因此,您需要在$email
和中跳过@
以使您的代码正常工作。
非常明确的解释。 –
在您的声明$email
您插入@dawn
这是由于引用。
为了避免任何麻烦,只需使用单引号是这样的:
my $email = '[email protected]';
my ($found) = $email =~ /(rise\@dawn\.com)/;
print "Found: $found";
啊,“内插”是指“评价一个意思”吗? –
插值,翻译,评估,你的名字。基本上我的意思是说,在双引号字符串perl内部将尝试查找变量($,%,@ ..)并填写它们的内容。 –
这很有道理。谢谢。 –
仅供参考,根据perldoc:
如果单引号使用S ''”,那么正则表达式和替换被视为单引号字符串。
所以下面的工作,太:
my $email = q{[email protected]};
my ($found) = $email =~ m'([email protected]\.com)';
print "Found: $found";
我通常使用\Q...\E
处理这一字面期间,顺便说一句,但我不想掩盖我试图点使。
'use strict;使用警告;' – friedo