正则表达式--可选分组匹配的默认值设置

正则表达式进行分组匹配,例如:
当我想匹配字符串末尾的!,不存在时,给一个默认值为not found

import re
str1 = "hello word!"
str2 = "hello word"
parttern = '(?P<first>hello) (?P<sec>word)(?P<thi>!)?'
vaule1 = re.search(parttern, str1)
print(vaule1.groupdict())
vaule2 = re.search(parttern, str2)
print(vaule2.groupdict())

结果为:

{'first': 'hello', 'sec': 'word', 'thi': '!'}
{'first': 'hello', 'sec': 'word', 'thi': None}

当我们想要未配置到thi的结果时,thi的值不为None.可以使用vaule2.groupdict('not found'),此时结果为{'first': 'hello', 'sec': 'word', 'thi': 'not found'}
同样, Match.groups()也支持设置默认值


注意

  • (?P<thi>!)?的'?'代表此分组是可选的,如果没有此标志,vaule2.groupdict()会报错

参考链接https://docs.python.org/3.10/library/re.html#module-re
posted @ 2023-02-14 16:57  TasteL  阅读(110)  评论(0编辑  收藏  举报