如何向带引号的正则 (qr) 表达式添加修饰符
有没有一种简单的方法可以将正则表达式修饰符(例如“i”)添加到带引号的正则表达式中?例如:
$pat = qr/F(o+)B(a+)r/;
$newpat = $pat . 'i'; # This doesn't work
我能想到的唯一方法是 print "$pat\n"
并返回 (?-xism:F(o+)B(a+)r)
并尝试使用替换删除 ?-xism:
中的“i”
Is there an easy way to add regex modifiers such as 'i' to a quoted regular expression? For example:
$pat = qr/F(o+)B(a+)r/;
$newpat = $pat . 'i'; # This doesn't work
The only way I can think of is to print "$pat\n"
and get back (?-xism:F(o+)B(a+)r)
and try to remove the 'i' in ?-xism:
with a substitution
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能将该标志放入已有的
qr
结果中,因为它受到保护。相反,使用这个:You cannot put the flag inside the result of
qr
that you already have, because it’s protected. Instead, use this:您可以修改现有的正则表达式,就像它是一个字符串一样,只要您之后重新编译它
OUTPUT
You can modify an existing regex as if it was a string as long as you recompile it afterwards
OUTPUT
看起来唯一的方法是对 RE 进行字符串化,用 (i-) 替换 (-i) 并重新引用它:
更新:perl 5.14 在 不同的方式,所以我的示例应该看起来像
但是我手头没有 perl 5.14,无法测试它。
UPD2:我也未能检查转义的左括号。
Looks like the only way is to stringify the RE, replace (-i) with (i-) and re-quote it back:
UPDATE: perl 5.14 quotes regexps in a different way, so my sample should probably look like
But I don't have perl 5.14 at hand and can't test it.
UPD2: I also failed to check for escaped opening parenthesis.