gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:09 25 4
gpt4 key购买 nike

我想匹配下面的字符串,

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)

关于python - 正则表达式匹配字符串 'xxx(yyy) (zzz(qqq))' 或 'xxx(yyy)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23165578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com