正则表达式匹配字符串'xxx(yyy) (zzz(qqq))'或'xxx(yyy)'



我想匹配下面的字符串,

str1: xxx(yyy) (zzz(qqq))
str2: xxx(yyy)

我写了一个只能匹配str1:的正则表达式

>>> s = re.compile(r'([^(]+)((.+))s*(([^(]+)((.+)))')
>>> m = s.match('xxx(yyy) (zzz(qqq))')
>>> for i in m.groups(): print i
...
xxx
yyy
zzz
qqq
>>> m = s.match('xxx(yyy)')
>>> for i in m.groups(): print i
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'

我该如何解决这个问题?

错误AttributeError: 'NoneType' object has no attribute 'groups'意味着您不能将groups方法应用于任何内容。

如果字符串与模式不匹配,则match返回None

您的正则表达式不正确,第三组和第四组可能不存在。最好在括号内或不在括号内查找任何字符串。

此外,match仅在该行的开头查找匹配的模式。您可以使用findall,但它会返回一个列表,因此finditer似乎更适合

这是已更正的正则表达式:s = re.compile(r'(?:(?([^()]+)(?([^()]+)))?s*)')

然而,使用finditer,您只需要寻找一个更简单的模式。所以下面的正则表达式是不同的:

import re
s=re.compile(r'(?([^s()]+))?')

string1='aa (bbbb) (cc (dddd) )'
string2='aa (bbbb) '

for string in [string1,string2]:
    print string
    m = s.finditer(string)
    for i in m: print i.group(1)

相关内容

最新更新