正则表达式非分组和条件块不匹配

2024-10-03 21:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的模式:

>>> pat = r'(?:.*)?(name)|nombres?'

当我测试时:

>>> import re
>>> re.search('nombre', pat).group()
>>> 'nombre'
>>> re.search('name', pat).group()
>>> 'name'

但是

>>> re.search('first_name', pat).group()
>>> *** AttributeError: 'NoneType' object has no attribute 'group'

Tags: nonameimportresearchobject模式group
2条回答

如前所述,参数交换应为:

re.search(pat, 'first_name').group()

我还想说,在尝试提取组匹配之前,您可能需要检查模式是否实际匹配:

result = re.search(pat, 'first_name')
if result:
   print(result.group())
else:
   print("not found")

你的论点顺序不对。首先是模式

相关问题 更多 >