我正在试验正则表达式,我已经阅读了一些关于断言的内容并看到了示例,但由于某种原因我无法让它工作。我正在尝试使用后视模式在以下模式之后得到这个词。
import re
s = '123abc456someword 0001abde19999anotherword'
re.findall(r'(?<=\d+[a-z]+\d+)[a-z]+', s, re.I)
结果应该是someword
和anotherword
但我得到错误:后视需要固定宽度的模式
感谢任何帮助。
最佳答案
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']
关于python - 在 python 中使用正则表达式断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24726801/