三功能于一身的正则表达式

时间:2013-04-11 22:01:52

标签: python regex regex-negation regex-lookarounds

我有一个非常具体的正则表达式请求。我需要匹配字符串

  • 包含“m _”,
  • 包含“phys_”(总是在“m _”之后的某些字符),
  • 以“形状”结尾。

当只使用第一个和最后一个标准时,这个正则表达式似乎工作正常:

^.*m_.*(?<!Shape)$

但是当我添加中间标准时,我迷失了。

3 个答案:

答案 0 :(得分:2)

import re

r = re.compile(r'^(?=.*m_)(?!.*m_.+phys_)(?!.+Shape$)')
print r.match("aaa")
print r.match("aaa m_ xx")
print r.match("aaa m_ xx Shape")
print r.match("aaa m_ xx phys_ foo")

基本上,原则是:

  ^
  (?= .* should be there)
  (?! .* should not be there)

答案 1 :(得分:1)

你想要的正则表达式是

^(?=.*m_)(?!.*phys_)(?!.*Shape$).*$

它将捕获整个字符串,每个条件都在它自己的预测中。您可以对其进行测试并查看www.debuggex.com上发生的事情的可视化。

答案 2 :(得分:0)

这可以通过Python中的普通字符串方法实现(为了清楚起见,我添加了括号):

("m_" in input) and ("phys_" not in input) and (not input.endswith("Shape"))

我将(总是在“m _”之后的某些字符)解释为“phys_”永远不会出现在“m_”之前,而不是允许“phys_”出现在“m_”之前的情况“m_”通过。