我的模式如下:
measurement = re.compile("(\d+(?:\.\d*)?)\s*x\s*(\d+(?:\.\d*)?)\s*(cm|mm|millimeter|centimeter|millimeters|centimeters)")
可以在句子和文档中多次看到。我想查找所有匹配项并将其替换为“MEASUREMENT”,我也希望将其值添加到列表中。
**Input_Text**: measuring 9 x 5 mm and previously measuring 8 x 6 mm
**Output**: measuring MEASUREMENT and previously measuring MEASUREMENT
**List**: 9 x 5 mm, 8 x 6 mm
到目前为止,我的代码在下面,但它只带来第一场比赛:
result = re.search(measurement, Input_Text)
if result:
Input_Text = Input_Text.replace(result, "MEASUREMENT")
答案 0 :(得分:1)
您可以使用re.sub()
进行替换,并使用re.findall()
获取所有匹配的字符串。
measurement = re.compile("(\d+(?:\.\d*)?)\s*x\s*(\d+(?:\.\d*)?)\s*(cm|mm|millimeter|centimeter|millimeters|centimeters)")
text = "measuring 9 x 5 mm and previously measuring 8 x 6 mm"
values = re.findall(pattern=measurement, string=text)
sub_text = re.sub(pattern=measurement, string=text, repl='MEASUREMENT')
>>> sub_text
'measuring MEASUREMENT and previously measuring MEASUREMENT'
>>> values
[('9', '5', 'mm'), ('8', '6', 'mm')]
答案 1 :(得分:1)
如果您不想两次解析字符串,可以使用re.sub
作为替换参数。使用此功能,您可以轻松填充匹配字符串列表。
pat = re.compile(r'\d+(?:\.\d*)?\s*x\s*\d+(?:\.\d*)?\s*(?:cm|mm|millimeters?|centimeters?)')
s = r'measuring 9 x 5 mm and previously measuring 8 x 6 mm'
l = []
def repl(m):
l.append(m.group(0))
return 'MEASUREMENT'
s = pat.sub(repl, s)