【问题标题】:Find all matches of a pattern and replace them in a text查找模式的所有匹配项并在文本中替换它们
【发布时间】:2018-02-11 21:26:36
【问题描述】:

我的模式如下:

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") 

【问题讨论】:

  • 使用re.finditer(pattern, string) ;).
  • 无论如何,你不能在文本中替换result;这是match object。
  • 那么为什么会有一个单独的findings_section 变量呢?和Input_Text一样吗?

标签: python regex match


【解决方案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')]

【讨论】:

    【解决方案2】:

    如果你不想解析你的字符串两次,你可以使用 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)
    

    【讨论】:

    猜你喜欢
    • 2013-04-16
    • 2017-09-11
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多