在Python中使用正则表达式断言
我正在尝试使用正则表达式(regex),并且对断言有一些了解,也看过一些例子,但不知为什么我就是无法让它正常工作。我想通过使用向后查找(look-behind)来获取特定模式后面的单词。
import re
s = '123abc456someword 0001abde19999anotherword'
re.findall(r'(?<=\d+[a-z]+\d+)[a-z]+', s, re.I)
我期望的结果是 someword
和 anotherword
但是我得到的错误是 error: look-behind requires fixed-width pattern
任何帮助都非常感谢。
3 个回答
0
还有一种简单的方法是通过前瞻来实现。
>>> import re
>>> s = '123abc456someword 0001abde19999anotherword'
>>> m = re.findall(r'[a-z]+(?= |$)', s, re.I)
>>> m
['someword', 'anotherword']
这个方法可以匹配一个或多个字母,并且后面的字符必须是一个空格或者是行的结束。
4
Python的re
模块在使用回顾查找时,只能处理固定长度的字符串。如果你想尝试使用可变长度的回顾查找,可以使用另一个regex
模块:
>>> import regex
>>> s = '123abc456someword 0001abde19999anotherword'
>>> regex.findall(r'(?i)(?<=\d+[a-z]+\d+)[a-z]+', s)
['someword', 'anotherword']
或者,干脆不使用回顾查找,直接使用捕获组( )
:
>>> import re
>>> s = '123abc456someword 0001abde19999anotherword'
>>> re.findall(r'\d+[a-z]+\d+([a-z]+)', s, re.I)
['someword', 'anotherword']