【问题标题】:RegEx - Find everything that does not contain a patternRegEx - 查找不包含模式的所有内容
【发布时间】:2016-02-03 15:46:57
【问题描述】:

我得到了这个正则表达式代码:

((\w)(\w)\3\2)

它匹配所有包含诸如 anna、otto、xyyx 之类的东西...

但我想匹配不包含这种模式的所有内容。 我该怎么做?

【问题讨论】:

  • 取决于正则表达式的风格和你想要做什么。请添加详细信息。
  • Regex 对于这种需求没有用处。您必须在编程语言中编写“不包含”代码,这比正则表达式“不包含”要简单得多。
  • 只使用这种模式进行拆分,稍后使用字符串方法加入。

标签: regex


【解决方案1】:

此问题已在此 SO post 上提出。你应该试试这个:

^((?!(\w)(\w)\3\2).)*$

【讨论】:

  • 这仅匹配不包含模式的整行/字符串,但不匹配与模式不匹配的任何内容。
  • OP 没有要求任何与模式不匹配的东西,而是要求所有不包含模式的东西。 在这种情况下,thing 的合理解释是 line,因此这个答案是完全正确的。
【解决方案2】:

最初我认为这种方法可以满足您的要求。但是由于下面@WiktorStribiżew 提出的原因,它不起作用。特别是 AAAB 和 ABBC 等测试字符串应该与以下字符串匹配,但

^((\w)(\w)(?!\3)(?!\2))

我的第二个想法是使用

^((\w)(\w)(?!\3\2))

这似乎确实有效。

新的测试程序。这会生成从 AAAA 到 ZZZZ 的所有可能字符串。然后使用非正则表达式检查来测试每个字符串是否应该匹配。最后,检查每个字符串是否符合正向

$findrepeats, ^((\w)(\w)(\3)(\2)) 匹配 abba

和负面的

$repeatnomatch ^((\w)(\w)(?!\3)(?!\2)) 匹配 ab[not b][not a]

use strict;
use warnings;

my @fourchar=('AAAA'..'ZZZZ'); 

my @norepeats=();

my @hasrepeats=();

for my $pattern ('AAAA' .. 'ZZZZ') {
  if (checkstring($pattern)) {
    push @hasrepeats, $pattern;
    } else {
    push @norepeats, $pattern;
    }
}

print scalar @hasrepeats, " strings with repeated abba\n";
print scalar @norepeats, " strings with ab[not b][not a]\n";



my $findsrepeats=qr/^((\w)(\w)(\3)(\2))/;
my $repeatnomatch=qr/^((\w)(\w)(?!\3\2))/;

for my $example (@hasrepeats) {
  die $example if (not($example=~$findsrepeats));
  die $example if ($example=~$repeatnomatch);
}

for my $example (@norepeats) {
  die $example if (not($example=~$repeatnomatch));
  die $example if ($example=~$findsrepeats);
}

print "pass\n";

sub checkstring {
  my $s=shift;
  my @element=split(//,$s);
  return ($element[0] eq $element[3]  && 
          $element[1] eq $element[2]);
}

运行上面的 perl 程序应该会产生这个输出

$ perl nr3.pl 
676 strings with repeated abba
456300 strings with ab[not b][not a]
pass

【讨论】:

  • 这是不正确的。你认为(?!\2)什么时候被执行?
  • @WiktorStribiżew 我猜它是从左到右评估的,所以首先设置捕获组,然后在此之后完成否定的前瞻断言。测试程序似乎按我的预期工作,所以如果你能给我提供错误否定或肯定的字符串,它可能会帮助我进一步理解这一点。谢谢
  • 你的假设是正确的,但是如果你打算匹配ab[not-b][not-a],这个正则表达式就不行,因为前瞻是在b之后的同一个地方执行的。 (?!\2) 检查b 之后的字符是否不是a。第四个字符可以是任何字符。
  • @WiktorStribiżew 好的,我已经设法弄清楚如何复制您所说的内容。如果我输入像“AAAB”这样的字符串,^((\w)(\w)(?!\3)(?!\2)) 不匹配,但应该匹配。我正在重写答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
  • 2017-10-27
  • 2018-03-15
  • 2016-04-05
  • 2019-06-28
  • 1970-01-01
相关资源
最近更新 更多