【问题标题】:Perl RE Matching: How can I use a variable for RE flags?Perl RE 匹配:如何将变量用于 RE 标志?
【发布时间】:2015-05-15 18:42:56
【问题描述】:

在 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

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

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

但是,在 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;);

但我想要一种更好的方法。

【问题讨论】:

  • @ThisSuitIsBlackNot,您建议的答案本身就是重复的
  • @ikegami 我选择了那个,因为我认为它(问题和答案)比它[据称]重复的帖子更符合这个问题。据我所知,重复链没有任何问题。
  • 无论如何,ikegami 给出的答案要好得多。我想避免整个eval 如果匹配。
  • @DavidW。只有我链接的帖子中的最后一个答案使用eval,并且该答案被否决为-2。其他三个答案都显示使用相同的语法 ikegami,尽管我同意 ikegami 的答案更好。

标签: regex perl


【解决方案1】:
$ 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)。

【讨论】:

  • 我学到了一些新东西。我从来不知道这一点,但它在 perlre 中,实际上可以追溯到 5.8.9 版:这些修饰符中的任何一个也可以使用 (?...) 构造嵌入到正则表达式本身中 谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 2011-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
相关资源
最近更新 更多