以下是Python代码:
import re
line="http://google.com"
procLine = re.match(r'(?<=http).*', line)
if procLine.group() == "":
print(line + ": did not match regex")
else:
print(procLine.group())
没有匹配成功,输出如下错误:
回溯(最近一次调用最后一次):文件
“C:/Users/myUser/Documents/myScript.py”,第 5 行,
在
if procLine.group() == "": AttributeError: 'NoneType' 对象没有属性 'group'
当我用 .* 替换正则表达式时,它工作正常,这表明正则表达式有错误,但是,https://regex101.com/ https://regex101.com/当我测试我的正则表达式和字符串的 python 风格时,它似乎匹配得很好。
有任何想法吗?
如果您将lookbehind转换为非捕获组,这应该可以工作:
In [7]: re.match(r'(?:http://)(.*)', line)
Out[7]: <_sre.SRE_Match object; span=(0, 17), match='http://google.com'>
In [8]: _.group(1)
Out[8]: 'google.com'
查找不起作用的原因是 - 作为拉温提到 https://stackoverflow.com/questions/46501800/python-3-regex-lookbehind-not-working/46501837?noredirect=1#comment79958019_46501837 - re.match
开始从start字符串,所以看看behind at the start字符串没有意义。
如果您坚持使用后视,请切换到re.search
:
In [10]: re.search(r'(?<=http://).*', line)
Out[10]: <_sre.SRE_Match object; span=(7, 17), match='google.com'>
In [11]: _.group()
Out[11]: 'google.com'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)