regex - Perl RE 匹配 : How can I use a variable for RE flags?

标签 regex perl

在 Perl 中:

my $string = "This is a test";
say "String matches" if $string =~ /this is a test/;          # Doesn't print
say "String sort of matches" if string =~ /this is a test/i;  # Prints

添加 i标记到 RE 匹配的末尾会导致匹配忽略大小写。

我有一个程序,我在其中指定要在单独的数据文件中匹配的正则表达式。这工作正常。但是,我希望能够扩展它并能够指定在检查匹配时使用的正则表达式标志。

但是,在 Perl 中,这些 RE 标志不能在标量中:
my $re_flags = "i";
my $string = "This is a test";
say "This sort of matches" if $string =~ /this is a test/$re_flags;

这导致:
Scalar found where operator expected at ,,, line ,,, near "/this is a test/$re_flags"  
(Missing operator before $re_flags?)
syntax error at ... line ..., near "/this is a test/$re_flags"
Execution of ... aborted due to compilation errors.

有没有办法在评估正则表达式时使用存储在标量变量中的 RE 标志?

我知道我可以使用 eval :
eval qq(say "This worked!" if \$string =~ /this is a test/$re_flags;);

但我想要一个更好的方法来做到这一点。

最佳答案

$ perl -E'say for qr/foo/, qr/foo/i'
(?^u:foo)
(?^ui:foo)

这只是表明
/foo/i
s/foo/bar/i

也可以写成
/(?i:foo)/
s/(?i:foo)/bar/

所以你可以使用
/(?$re_flags:foo)/
s/(?$re_flags:foo)/bar/

这仅适用于与正则表达式 (a, d, i, l, m, p, s, u, x) 有关的标志,而不适用于与匹配运算符 (c, g, o) 或替换有关的标志运算符 (c, e, g, o, r)。

关于regex - Perl RE 匹配 : How can I use a variable for RE flags?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30266625/

相关文章:

Python正则表达式替换字符串

MySQL:正则表达式和通配符

javascript - 在 Google Maps API 中显示多个 map 标记

perl - 为什么 `$@` 不可信?

perl DBIx sqlite {sqlite_unicode=>1}?

c++ - 将字符串中的数据提取到映射中的有效方法是什么?

java - 修剪字符串以获得java中的第二个单词,第三个单词和第四个单词?

perl - 有没有办法从 XS 访问 perl 中的特殊标记?

php - 查找并替换 MySQL 表中的大括号标签

java - 将 a^xb^x 与正则表达式匹配