Perl 正则表达式与变量不匹配相同的文本
有人可以向我解释为什么以下打印“失败”吗?解决方法是什么?
my $test1 = "/k?user";
my $test2 = "/k?user";
if ($test1 =~ m/$test2/) {
print "match";
}
else {
print "fail";
}
如果我将 $test1
和 $test1
更改为 "/k?"
,则匹配有效。
显然它与 ?
后面的文本有关。但是,我试图匹配的变量中有问号,我宁愿不必把所有东西拆开,匹配各个部分,然后重建所有东西。
Could someone explain to me why the following prints "fail"? And what the workaround is?
my $test1 = "/k?user";
my $test2 = "/k?user";
if ($test1 =~ m/$test2/) {
print "match";
}
else {
print "fail";
}
If I change $test1
and $test1
to "/k?"
, the match works.
Clearly it has something to do with text following the ?
. But, the variables I am trying to match have question marks in them, and I would rather not have to take everything apart, match the pieces, and then reconstruct everything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
?
是正则表达式中的特殊字符。使用 quotemeta:?
is a special character in a regex. Use quotemeta:要(仅)匹配
需要使用该模式,
因为“
?
”在正则表达式模式中与自身不匹配。您需要对其进行转义(使用“\?
”)以使其匹配“?
”,并转义特殊字符(例如“?") 可以使用
quotemeta
来完成。quotemeta
也可以通过双引号字符串文字和正则表达式模式文字中的\Q..\E
进行访问。(toolic 之前建议的解决方案也将匹配“
!/k?userf
”。)To (only) match
one needs to use the pattern
because "
?
" doesn't match itself in a regex pattern. You need to escape it (use "\?
") for it to match a "?
", and escaping the special characters (such as "?
") can be done usingquotemeta
.quotemeta
can also be accessed via\Q..\E
in double-quoted string literals and regex pattern literals.(The solution previously suggested by toolic would also match "
!/k?userf
".)