Regex Negative Lookbehind 在 PCRE 中有效,但在 Python 中无效

问题描述 投票:0回答:1

模式

(?<!(asp|php|jsp))\?.*
适用于PCRE,但不适用于Python。

那么我该怎么做才能让这个正则表达式在 Python 中工作? (蟒蛇 2.7)

python regex pcre negative-lookbehind
1个回答
25
投票

对我来说效果很好。你可能用错了吗?确保使用

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)\?.*
© www.soinside.com 2019 - 2024. All rights reserved.