【问题标题】:Regex only one alternation正则表达式只有一个交替
【发布时间】:2015-01-16 10:02:30
【问题描述】:

正则表达式:(simple|complex)
文字:using simple with key value pairs using complex with key value pairs using simple with key value pairs

如果simple 值被使用而不是两次,有没有办法只匹配一次?

【问题讨论】:

  • 不要使用全局修饰符,或者^(?:(?!\bsimple\b|\bcomplex\b).)*\K(?:simple|complex)regex101.com/r/sY6eW6/3
  • 你能解释一下吗Is there any way to match only once the simple value if it's used and not two times?
  • 你是说要成功匹配,字符串必须只出现一次simple,并且只出现一次complex?如果是这样,您可以使用:^(?=(?:(?!simple).)*?(?:simple)(?:(?!simple).)*$)(?=^(?:(?!complex).)*?(?:complex)(?:(?!complex).)*$).*?$
  • 我想要的是,如果它发现简单,那么它应该只匹配一次,或者如果它发现复杂,它应该只匹配一次,如果它发现简单和复杂,它应该只匹配一次。
  • 仅使用 2 个单独的匹配项而不使用全局标志?

标签: regex


【解决方案1】:
#!/usr/bin/perl
#
use Data::Dumper;

my @ex=qw(simple complex simplycomplex complexcomplexbutsimple simplebutcomplex);

sub runexamples {
  my $qr=shift;
  my @matches;
  for my $example (@ex) {
    push @matches, [($example =~ /$qr/)];
  }
  return \@matches;
}

print Dumper(runexamples(qr/(complex|simple)/));

如果运行此程序会产生以下输出

$VAR1 = [
          [
            'simple'
          ],
          [
            'complex'
          ],
          [
            'complex'
          ],
          [
            'complex'
          ],
          [
            'simple'
          ]
        ];

未设置全局修饰符,“复杂”和“简单”都被正确检测到。如果第一个字符串是“simple”,那么即使字符串“complex”也存在,也会报告它自己。

【讨论】:

    【解决方案2】:

    以下表达式将仅匹配其中包含 simplecomplex 的行,但前提是其中任一仅出现一次:

    ^(?=(?:(?!simple).)*?(?:(?:simple)(?:(?!simple).)*?$|$))(?=.*?(?:simple|complex))(?=(?:(?!complex).)*?(?:(?:complex)(?:(?!complex).)*?$|$)).*?$

    确保无论您使用什么来实现此表达式都处于多行模式(大多数情况下默认为多行模式)。

    匹配:

    using simple with complex here
    eggs are both complex and simple all at once
    simple
    complex
    some simple things
    some complex things
    

    不匹配:

    this is irrelevant 
    eggs are both complex and simple all at once said simple simon
    simple simple
    complex complex
    

    表达式可以分解为三个要求:

    • (?=.*?(?:simple|complex)) 该行必须包含“简单”或“复杂”
    • (?=(?:(?!simple).)*?(?:(?:simple)(?:(?!simple).)*?$|$))该行只能有一个simple或没有simple
    • (?=(?:(?!complex).)*?(?:(?:complex)(?:(?!complex).)*?$|$))该行只能有一个复杂的出现或没有出现

    【讨论】:

    • 这看起来过于复杂了。 ^(?!.*simple.*simple|.*complex.*complex).*(simple|complex).* 也会这样做。
    • @TimPietzcker 谢谢,更容易阅读,效率更高
    猜你喜欢
    • 1970-01-01
    • 2011-01-14
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多