gpt4 book ai didi

python - 无效的表达式 sre_constants.error : nothing to repeat

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:55 26 4
gpt4 key购买 nike

我正在尝试匹配输出变量中的数据,正在寻找匹配 * 之后的单词,正在尝试以下方式但遇到错误,如何解决?

import re
output = """test
* Peace
master"""
m = re.search('* (\w+)', output)
print m.group(0)

错误:-

Traceback (most recent call last):
File "testinglogic.py", line 7, in <module>
m = re.search('* (\w+)', output)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 146, in search
return _compile(pattern, flags).search(string)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 251, in _compile
raise error, v # invalid expression
sre_constants.error: nothing to repeat

最佳答案

第一个修复方法是转义 *,因为您希望引擎按字面意思(作为星号)对待它,所以您使用反斜杠转义它。

另一个建议是使用lookbehind,所以你不需要使用另一个捕获组:

>>> re.search('(?<=\*\s)\w+', output).group()
'Peace'

关于python - 无效的表达式 sre_constants.error : nothing to repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48837759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com