加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – Perl RE匹配:如何将变量用于RE标志?

发布时间:2020-12-14 06:03:26 所属栏目:百科 来源:网络整理
导读:在Perl中: my $string = "This is a test";say "String matches" if $string =~ /this is a test/; # Doesn't printsay "String sort of matches" if string =~ /this is a test/i; # Prints 将i标志添加到RE匹配的末尾会导致匹配忽略大小写. 我有一个程序,
在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,o,r).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读