【问题标题】:How can I combine a positive and negative condition in a regex?如何在正则表达式中组合正负条件?
【发布时间】:2009-08-20 20:47:20
【问题描述】:

我对正则表达式相当陌生,需要一些帮助。我需要在 Perl 中使用正则表达式过滤一些行。我要将正则表达式传递给另一个函数,所以它需要在一行中完成。

我只想选择包含 "too long" 并且不以 "SKIPPING" 开头的行

这是我的测试字符串:

由于到期时间太长而跳过此债券
TKIPPING此债券,因为到期时间太长
由于到期时间太长,因此拍打该债券
你好这个成熟度太长了
太长了
你好

正则表达式规则应该在“太长”时匹配以下内容:

由于到期时间太长而跳过此债券
由于到期时间太长,因此拍打该债券
你好这个成熟度太长了
太长了

它应该跳过:

“你好”,因为它不包含“太长”
“由于到期时间太长而跳过此债券”,因为它包含“跳过”

【问题讨论】:

    标签: regex perl regex-negation lookahead negative-lookahead


    【解决方案1】:
    /^(?!SKIPPING).*too long/
    

    【讨论】:

    • 这就是在 Perl 中进行负向后视的方式。没有< 符号。
    • 实际上,这是一个否定的前瞻。否定的lookbehind确实有<...语法是(?<!pattern)
    【解决方案2】:

    就个人而言,我会将其作为两个单独的正则表达式来执行,以使其更清晰。

    while (<FILE>)
    {
      next if /^SKIPPING/;
      next if !/too long/;
    
       ... do stuff
    }
    

    【讨论】:

    • “不是答案”是什么意思?它完全实现了他想要的,只是不完全按照他的想法去做。对我来说,这是一个答案。
    【解决方案3】:

    我怀疑你可能在一个正则表达式之后但是我更喜欢像这样拆分成更易读的东西:

    use strict;
    use warnings;
    
    for my $line ( <DATA> ) {
        next  if $line =~ m/^SKIPPING/;
        next  if $line !~ m/too long/;
    
        # do something with $line
        chomp $line;
        say "Found: ", $line, ':length=', length( $line );
    }
    
    __DATA__
    SKIPPING this bond since maturity too long
    TKIPPING this bond since maturity too long
    SLAPPING this bond since maturity too long
    Hello this maturity too long
    this is too long
    hello there
    

    【讨论】:

      【解决方案4】:

      使用前瞻;见this explanation of regex lookaround

      ^(?!SKIPPING).*too long
      

      【讨论】:

      • 不幸的是,该网站的否定后视语法完全错误。
      • @Daniel:不,不是。我想你在这里很困惑。
      • @Daniel:这个网站怎么错了?在我知道的每一种正则表达式风格中,负向后看都采用(?&lt;!...) 的形式(支持向后看)。也许您正在考虑否定的lookahead(?!...)
      • @Alan M:该网站确实是正确的,我的回答是否定的前瞻,但我认为值得一提的是,一些(尽管很少)正则表达式风格使用语法 (...)\ @
      【解决方案5】:
      /^(?<!SKIPPING).*too long$/
      

      匹配您要查找的行。末尾的美元符号使其仅匹配以“太长”结尾的字符串。

      希望这会有所帮助!

      【讨论】:

      • 在 JS 中为我​​工作。感叹号 (!) 在我的 javascript 代码中不起作用。
      【解决方案6】:

      使用否定的lookbehind:

      (?<!^SKIPPING)too long$
      

      【讨论】:

      • 我不确定 ?
      • 您不能使用可变长度的lookbehind。
      • @Jeremy Powell:不,匹配因为有几个地方 (?
      猜你喜欢
      • 1970-01-01
      • 2011-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多