无效表达式 sre_constants.error: nothing to repeat。

3

我正在尝试匹配输出变量中的数据,希望能匹配*后面的单词,我尝试了以下方式,但遇到了错误,怎样解决呢?

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
1个回答

3
第一种修复方法是转义*,因为您希望引擎将其视为文字(星号),所以您需要用反斜杠进行转义。
另一个建议是使用回顾后发,这样您就不需要使用另一个捕获组:
>>> re.search('(?<=\*\s)\w+', output).group()
'Peace'

@coldspeed - ?<= 表示什么意思? - Jeremyapple
@Jeremyapple 这是正则表达式中的后顾语法。您可以指定在您想要的内容之前出现的模式,但不希望它被捕获。 - cs95

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接