【问题标题】:Perl regex option stored in variable [duplicate]Perl正则表达式选项存储在变量中[重复]
【发布时间】:2018-09-19 12:04:50
【问题描述】:

有没有办法将正则表达式及其选项存储在标量中?就我而言,我有这个:

{
  regex => 'this is'.CONSTANT_STRING'. a regex',
  someOtherKey => someOtherValue
}

匹配时我这样做:

if($line =~ m/$hash->{regex}/i) {
...
}

效果很好。

但我需要的是选项 /i 存储在正则表达式本身中,所以我可以这样做

if($line =~ $hash->{regex}) {
...
}

但是当我尝试像这样将正则表达式存储在哈希中时:

regex => '/this is a regex/i',

这行不通。我玩过

评估,qr

等等。这有可能做到吗?

【问题讨论】:

  • 你试过这样存储吗?:regex => qr/this is a regex/i(带qr,不带引号)

标签: regex perl options


【解决方案1】:

您可以将qr 与修饰符一起使用

regex => qr/this is a regex/i,

或者你可以通过?:内联修饰符

regex => '(?i:this is a regex)',
# or
regex => qr/(?i:this is a regex)/,

【讨论】:

  • regex => '(?i:this is a regex)' 为我做了。谢谢。
猜你喜欢
  • 2014-01-06
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
相关资源
最近更新 更多