如果不包含某种模式,我如何匹配所有内容?

时间:2012-04-24 09:51:21

标签: regex

我有这样的格式的字符串。我希望匹配开头没有abcd的字符串。

abcd.efgh.ijkl
pqrs.efgh.ijkl
xyz.efgh.ijkl

我想出了这个表达式(?<!abcd).efgh.ijkl http://rubular.com/r/jyZMIJxoNz

它有点满足我的需要。它与.efgh.ijklpqrs.efgh.ijkl的{​​{1}}部分匹配,并忽略xyz.efgh.ijkl。但我也希望它与abcd.efgh.ijklpqrs部分匹配。

我尝试像xyz那样制作条件,但它甚至不被认为是正则表达式。语法有什么问题?是不是说“如果它以abcd开头,那么(?(?<!abcd)|.*\.efgh.ijkl)或其他所有内容都匹配到blank

5 个答案:

答案 0 :(得分:2)

[^\s]*(?<!abcd).efgh.ijkl

http://rubular.com/r/h11pUhuYSD

应该适合您的目的。如果目标是一个更长的字符串,它甚至匹配。

答案 1 :(得分:1)

你想为此使用前瞻,而不是后视。

^(?!abcd\.)[a-z]+(?:\.[a-z]+)+$

主正则表达式是^[a-z]+(?:\.[a-z]+)+$,它匹配由两个或多个由点分隔的字母组成的字符串。在开始锚之后的前瞻确保第一个丛不是abcd

请注意,如果它真的是Ruby,那么^$锚点。这意味着正则表达式将从字符串中取出第二行:

foo
pqrs.efgh.ijkl
bar

......这可能不是你想要的。为了确保只匹配Ruby中的整个字符串,您应该使用字符串锚点\A\z

\A(?!abcd\.)[a-z]+(?:\.[a-z]+)+\z

至于你尝试使用条件,Ruby似乎不支持它们。但无所谓,无论如何都不会有效。

答案 2 :(得分:0)

试试这个:

(?m)^(?!abcd).+$

说明:

<!--
(?m)^(?!abcd).+$

Options: ^ and $ match at line breaks

Match the remainder of the regex with the options: ^ and $ match at line breaks (m) «(?m)»
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!abcd)»
   Match the characters “abcd” literally «abcd»
Match any single character that is not a line break character «.+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
-->

答案 3 :(得分:0)

试试这个:

[^"(a.+b)|(b.+c)|(c.+d)|"].* 

http://rubular.com/r/51OShSXwUz

答案 4 :(得分:0)

负面的外观很有趣,它们是一个很好的工具。

但是,如果您只想匹配不以abcd开头的整行,一个简单的方法是匹配执行的行从abcd开始,然后选择匹配的每一行。

示例(python):

In [1]: lines = [
   ...: "abcd 1",
   ...: "abcd 2",
   ...: "pqrs 3",
   ...: "pqrs 4" ]

In [2]: import re

In [4]: for line in lines:
   ...:     if re.match(r"^abcd.+$", line):
   ...:         pass # do nothing
   ...:     else:
   ...:         print (line)
   ...: 

pqrs 3
pqrs 4

此外,如果您要查找的abcd是文字字符串(即字面意思abcd,而不是其他正则表达式),那么字符串操作将更快更容易理解:< / p>

In [5]: for line in lines:
   ...:     if not(line.startswith('abcd')):
   ...:         print(line)
   ...: 

pqrs 3
pqrs 4
相关问题