为什么正则表达式在python中返回错误?

Gat*_*ath 3 python regex

我在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'

kgi*_*kis 5

发生这种情况是因为正则表达式不匹配.因此m是None,当然你不能访问组[0].在尝试访问组成员之前,您需要首先测试搜索是否成功.


tzo*_*zot 5

两个问题:

  1. 您的模式不匹配,因此m设置为None,并且None没有group属性。

  2. 我相信你的意思是:

    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"" 字符串通常是一个好主意。)