In 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
Adding the i
flag onto the end of the RE match causes the match to ignore case.
将i标志添加到RE匹配的末尾会导致匹配忽略大小写。
I have a program where I specify the regular expression to match in a separate data file. This works fine. However, I'd like to be able to expand that and be able to specify the regular expression flags to use when checking for a match.
我有一个程序,我在其中指定要在单独的数据文件中匹配的正则表达式。这很好用。但是,我希望能够扩展它并能够指定在检查匹配时使用的正则表达式标志。
However, in Perl, those RE flags cannot be in a scalar:
但是,在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;
This results in:
这导致:
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.
Is there a way to use RE flags stored in a scalar variable when evaluating a regular expression?
在评估正则表达式时,有没有办法使用存储在标量变量中的RE标志?
I know I can use eval
:
我知道我可以使用eval:
eval qq(say "This worked!" if \$string =~ /this is a test/$re_flags;);
But I'd like a better way of doing this.
但我想要一个更好的方法来做到这一点。
1 个解决方案
#1
9
$ perl -E'say for qr/foo/, qr/foo/i'
(?^u:foo)
(?^ui:foo)
This just goes to show that
这只是表明了这一点
/foo/i
s/foo/bar/i
can also be written as
也可以写成
/(?i:foo)/
s/(?i:foo)/bar/
so you could use
所以你可以使用
/(?$re_flags:foo)/
s/(?$re_flags:foo)/bar/
This will only work for flags that pertain to the regular expression (a, d, i, l, m, p, s, u, x) rather than flags that pertain to the match operator (c, g, o) or the substitution operator (c, e, g, o, r).
这仅适用于与正则表达式(a,d,i,l,m,p,s,u,x)相关的标志,而不适用于与匹配运算符(c,g,o)或替换相关的标志运算符(c,e,g,o,r)。
#1
9
$ perl -E'say for qr/foo/, qr/foo/i'
(?^u:foo)
(?^ui:foo)
This just goes to show that
这只是表明了这一点
/foo/i
s/foo/bar/i
can also be written as
也可以写成
/(?i:foo)/
s/(?i:foo)/bar/
so you could use
所以你可以使用
/(?$re_flags:foo)/
s/(?$re_flags:foo)/bar/
This will only work for flags that pertain to the regular expression (a, d, i, l, m, p, s, u, x) rather than flags that pertain to the match operator (c, g, o) or the substitution operator (c, e, g, o, r).
这仅适用于与正则表达式(a,d,i,l,m,p,s,u,x)相关的标志,而不适用于与匹配运算符(c,g,o)或替换相关的标志运算符(c,e,g,o,r)。