Python 正则表达式负回顾 [英] Python Regex Negative Lookbehind

查看:55
本文介绍了Python 正则表达式负回顾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模式 (?<!(asp|php|jsp))\?.* 在 PCRE 中有效,但在 Python 中无效.

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

解决方案

它对我来说非常好.你可能用错了吗?确保使用 re.search 而不是 re.match:

<预><代码>>>>进口重新>>>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 对象在 0x0000000002DCB098>

这正是您的模式应该表现的方式.正如 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆