我在python中尝试以下正则表达式,但它返回错误
import re
...
#read a line from a file to variable line
# loking for the pattern 'WORD' in the line ...
m=re.search('(?<=[WORD])\w+',str(line))
m.group(0)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
AttributeError:'NoneType'对象没有属性'group'
两个问题:
您的模式不匹配,因此m
设置为None
,并且None
没有group
属性。
我相信你的意思是:
m= re.search(r"(?<=WORD)\w+", str(line))
Run Code Online (Sandbox Code Playgroud)
输入的内容,或
m= re.search(r"(?P<WORD>\w+)", str(line))
Run Code Online (Sandbox Code Playgroud)
前者匹配“WORDabc def”中的“abc”;后者匹配“abc def”中的“abc”,并且匹配对象将包含一个.group("WORD")
包含“abc”的对象。(指定正则表达式时,使用 r"" 字符串通常是一个好主意。)