简体   繁体   English

Python正则表达式负面观察

[英]Python Regex Negative Lookbehind

The pattern (?<!(asp|php|jsp))\\?.* works in PCRE, but it doesn't work in Python. 模式(?<!(asp|php|jsp))\\?.*在PCRE中有效,但在Python中不起作用。

So what can I do to get this regex working in Python? 那么我该怎么做才能让这个正则表达式在Python中运行? (Python 2.7) (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 : 确保使用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>

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() . 正如glglgl所提到的,如果将Match对象分配给变量(比如m )然后调用m.group() ,则可以得到匹配。 That yields ?1=123 . 产生?1=123

By the way, you can leave out the inner parentheses. 顺便说一句,你可以省略内括号。 This pattern is equivalent: 这种模式是等效的:

(?<!asp|php|jsp)\?.*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM