【问题标题】:How can I include a variable in a match regular expression in Perl, and check if the variable is NOT in the string?如何在 Perl 的匹配正则表达式中包含变量,并检查该变量是否不在字符串中?
【发布时间】:2012-06-16 20:29:01
【问题描述】:

我想在 Perl 中的匹配正则 r 表达式中包含一个变量,并检查该变量是否不在字符串中。

链接here 指示如何包含变量,但如果变量不匹配,我很难测试。当然,我可以像这样否定 if 条件:

if (!($string =~ m/$Myvar/)) {
# Do some code here
}

但我确信在正则表达式匹配中必须有一种方法。 有什么想法吗?

提前感谢您的帮助。

【问题讨论】:

    标签: regex string perl variables match


    【解决方案1】:

    使用!~ 运算符。

    if ($string !~ m/$Myvar/) {
    # Do some code here
    }
    

    或者使用index 并完全避免使用正则表达式引擎。即使$Myvar 包含正则表达式引擎特别处理的字符,这也将起作用。

    if ( index($string, $Myvar) < 0 ) {
    # Do some code here
    }
    

    【讨论】:

      【解决方案2】:

      否定结果有什么问题?

      “否定匹配”(需要否定 lookahead assertion)使您的正则表达式更加复杂:

      if ($string =~ m/^(?!.*$Myvar)/s) {
          # Do some code here
      }
      

      【讨论】:

        猜你喜欢
        • 2015-03-02
        • 2014-08-06
        • 1970-01-01
        • 1970-01-01
        • 2016-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-20
        相关资源
        最近更新 更多