咨询:如何将Python正则匹配位置返回逻辑改写为单行Return语句
实现单行Return的正则匹配位置提取
嘿,我懂你想要把正则匹配位置的逻辑浓缩成一行return语句的需求啦!其实利用Python的列表推导式加上布尔短路特性,就能轻松实现你想要的效果。
单行实现代码
import re def get_match_positions(pattern, text): return [(match.start(), match.end()) for match in re.finditer(pattern, text)] or None
代码解释
re.finditer(pattern, text):返回一个迭代器,包含所有匹配正则模式的Match对象- 列表推导式
[(match.start(), match.end()) for match in ...]:遍历每个匹配对象,提取其起始和结束索引组成元组,生成结果列表 or None:利用Python的布尔判断特性——空列表会被视为False,所以当没有匹配项时,表达式会返回None;有匹配项时则直接返回生成的位置列表
测试示例
# 有匹配的情况 print(get_match_positions(r'\w+', 'Hello, World!')) # 输出 [(0, 5), (7, 12)] # 无匹配的情况 print(get_match_positions(r'\d+', 'Hello, World!')) # 输出 None
这个写法完美符合你想要的return [(match.start(), match.end())...]类似结构,同时满足无匹配时返回None的要求~
内容的提问来源于stack exchange,提问作者Aaron
相关产品推荐
相关产品推荐

