我使用smartmatch检查字符串是否与正则表达式模式匹配。在我决定将正则表达式存储在文本文件中后,它停止工作。
my $str = '123456, some text.';
my $regex = qr/^\d+, some text\.$/;
print "Regex: $regex\n";
此时,打印的正则表达式为(?^:^\d+, some text\.$)
. 我将它复制粘贴到一个文件中,然后让代码读取文件并检索存储在$regexFromFile
.
以下行证实了这一点,$regex
并且$regexFromFile
是相同的,然后我继续以$str
各种方式针对正则表达式进行测试。
print 'Is regex equal to regexFromFile? ' . ($regex eq $regexFromFile) . "\n";
print 'Does str match regex using =~ ? ' . ($str =~ $regex) . "\n";
print 'Does str match regexFromFile using =~ ? ' . ($str =~ $regexFromFile) . "\n";
print 'Does str match regex using ~~ ? ' . ($str ~~ $regex) . "\n";
print 'Does str match regexFromFile using ~~ ? ' . ($str ~~ $regexFromFile) . "\n";
该代码的最后一行与前三行的行为不同。
这是代码的完整输出:
Regex: (?^:^\d+, some text\.$)
Is regex equal to regexFromFile? 1
Does str match regex using =~ ? 1
Does str match regexFromFile using =~ ? 1
Does str match regex using ~~ ? 1
Does str match regexFromFile using ~~ ?
(注意最后没有1
。)
编辑:要回答评论,这里是文件的读取方式。
open(my $FILEHANDLE, 'file.txt') or die "Error: Could not open file.\n";
my @content = <$FILEHANDLE>;
close($FILEHANDLE) or print "Could not close file.\n";
my @content_woEol = ();
foreach my $line (@content){
$line =~ s/\s*$//;
push(@content_woEol, $line);
}
my $regexFromFile = $content_woEol[0];
的结果qr//
实际上是一个预编译的正则表达式。像您一样将打印的正则表达式复制粘贴到文件中,然后从文件中读取它,这不是问题。如果直接在代码中编写此行,您会遇到相同的行为:
my $regexFromFile = '(?^:^\d+, some text\.$)';
如果您想在这里使用 smatmatch,我建议您执行以下操作:
my $str = '123456, some text.';
my $regex = '^\d+, some text\.$';
# Manually store this in the file: ^\d+, some text\.$
# Read $regexFromFile from the file
print 'Does str match regex using =~ ? ' . ($str =~ /$regex/) . "\n";
print 'Does str match regexFromFile using =~ ? ' . ($str =~ /$regexFromFile/) . "\n";
print 'Does str match regex using ~~ ? ' . ($str ~~ /$regex/) . "\n";
print 'Does str match regexFromFile using ~~ ? ' . ($str ~~ /$regexFromFile/) . "\n";
注意额外的/.../
. 输出:
Does str match regex using =~ ? 1
Does str match regexFromFile using =~ ? 1
Does str match regex using ~~ ? 1
Does str match regexFromFile using ~~ ? 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句