Python正则表达式获取匹配的下标
0. 需求
获取Python正则表达式匹配的下标。如:有一个句子"One plus two equals to three",需要根据模板"X plus Y equals to Z"提取出变量"X"、"Y"和"Z"以及它们在句子中的位置(下标)。
1. 解决方案
要点:
- 使用
finditer
函数; - 使用循环取下标;
代码如下:
import re
def get_items_idx(match_obj, with_words: bool = True) -> dict:
""" 获取下标
Parameters
----------
:param match_obj: 匹配之后的对象
:param with_words: bool (default=True), 是否需要返回对应的单词(默认为True)
:return: dict of list. 返回的格式{"idx": [], "words": []}
"""
ret = dict()
ret["idx"] = []
ret["words"] = []
if match_obj:
for obj in match_obj:
item_num = len(obj.groups())
for idx in range(1, item_num + 1):
ret["idx"].append(obj.span(idx))
if with_words:
ret["words"].append(obj.group(idx))
else:
print("failed!")
return ret
text = "One plus two equals to three."
match_obj = re.finditer(r"(.*?) plus (.*?) equals to (.*).", text, re.M | re.I)
print(get_items_idx(match_obj))
运行结果:
{‘idx’: [(0, 3), (9, 12), (23, 28)], ‘words’: [‘One’, ‘two’, ‘three’]}