Python 正则表达式负回顾 [英] Python Regex Negative Lookbehind
问题描述
模式 (?<!(asp|php|jsp))\?.*
在 PCRE 中有效,但在 Python 中无效.
那么我该怎么做才能让这个正则表达式在 Python 中工作?(Python 2.7)
它对我来说非常好.你可能用错了吗?确保使用 re.search
而不是 re.match
:
这正是您的模式应该表现的方式.正如 glglgl 所提到的,如果您将该 Match
对象分配给一个变量(比如 m
),然后调用 m.group()
.这产生 ?1=123
.
顺便说一下,您可以省略内括号.这个模式是等价的:
(?
The pattern (?<!(asp|php|jsp))\?.*
works in PCRE, but it doesn't work in Python.
So what can I do to get this regex working in Python? (Python 2.7)
It works perfectly fine for me. Are you maybe using it wrong? Make sure to use re.search
instead of 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>
Which is exactly how your pattern should behave. As glglgl mentioned, you can get the match if you assign that Match
object to a variable (say m
) and then call m.group()
. That yields ?1=123
.
By the way, you can leave out the inner parentheses. This pattern is equivalent:
(?<!asp|php|jsp)\?.*
这篇关于Python 正则表达式负回顾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!