Python正则表达式负面观察

时间:2012-12-19 08:05:11

标签: python regex pcre negative-lookbehind

模式(?<!(asp|php|jsp))\?.*在PCRE中有效,但在Python中不起作用。

那么我该怎么做才能让这个正则表达式在Python中运行? (Python 2.7)

1 个答案:

答案 0 :(得分:12)

它对我来说非常好。你可能错了吗?请务必使用re.search代替re.match

>>> import re
>>> s = 'somestring.asp?1=123'
>>> re.search(r"(?<!(asp|php|jsp))\?.*", s)
>>> s = 'somestring.xml?1=123'
>>> re.search(r"(?<!(asp|php|jsp))\?.*", s)
<_sre.SRE_Match object at 0x0000000002DCB098>

您的模式应该如何表现。正如glglgl所提到的,如果您将Match对象分配给变量(例如m)然后调用m.group(),则可以获得匹配。这会产生?1=123

顺便说一下,你可以省略内括号。这种模式是等效的:

(?<!asp|php|jsp)\?.*
相关问题