我在创建寻找类似于 的字符串的正则表达式时遇到了困难F:\work\object\src
。我创建了以下我尝试过的方法的演示。请注意,$match 来自数据库字段,因此它被定义为字符串,然后由 qr 运算符使其成为 RE。
#!/opt/perl/bin/perl
use Try::Tiny;
use Data::Dumper::Concise;
my $str = 'F:\work\object\src';
my @matches = (
"\b F\\:\\work\\object\\src \b",
'\b F\:\work\object\src \b',
q{\b F\\:\\work\\object\\src \b},
q{\b\QF:\work\object\src\E \b},
q{\b F\\:\\work\\\\object\\src \b},
qq{\b F\\:\\work\\\\object\\src \b},
);
my $i = 0;
foreach my $match (@matches) {
print "attempt ".$i++."\n";
try {
my $re = qr{($match)}xims;
print "Built successfully.\n";
if ($str =~ /$re/) {
print "Match\n";
}
else {
print "But did not match!\n";
print Dumper($re);
}
}
catch {
print "$match failed to build re\n";
print "$_\n";
};
}
该测试程序的输出如下:
attempt 0
F\:\work\object\src failed to build re
Missing braces on \o{} in regex; marked by <-- HERE in m/ F\:\work\o <-- HERE bject\sr)/ at ./reparse.pl line 20.
attempt 1
\b F\:\work\object\src \b failed to build re
Missing braces on \o{} in regex; marked by <-- HERE in m/(\b F\:\work\o <-- HERE bject\src \b)/ at ./reparse.pl line 20.
attempt 2
\b F\:\work\object\src \b failed to build re
Missing braces on \o{} in regex; marked by <-- HERE in m/(\b F\:\work\o <-- HERE bject\src \b)/ at ./reparse.pl line 20.
attempt 3
\b\QF:\work\object\src\E \b failed to build re
Missing braces on \o{} in regex; marked by <-- HERE in m/(\b\QF:\work\o <-- HERE bject\src\E \b)/ at ./reparse.pl line 20.
attempt 4
Built successfully.
But did not match!
qr/(\b F\:\work\\object\src \b)/msix
attempt 5
Built successfully.
But did not match!
qr/ F\:\work\\object\src)/msi
尝试 4 和 5 似乎转义了 \o,但无法匹配字符串。希望有人能帮助我制作一个可用的字符串。