我正在尝试匹配输出变量中的数据,希望能匹配*
后面的单词,我尝试了以下方式,但遇到了错误,怎样解决呢?
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
m = re.search('\* (\w+)', output)
。在星号前添加反斜杠。星号用于检查正则表达式中的重复项。因此,要实际匹配星号,必须使用转义字符。 - Sruthi