Python正则表达式负面观察

Mat*_*son 13 python regex pcre negative-lookbehind

该模式(?<!(asp|php|jsp))\?.*适用于PCRE,但它在Python中不起作用.

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

Mar*_*der 16

它对我来说非常好.你可能错了吗?确保使用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>
Run Code Online (Sandbox Code Playgroud)

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

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

(?<!asp|php|jsp)\?.*
Run Code Online (Sandbox Code Playgroud)