首页 > 解决方案 > 正则表达式匹配可变数量的注释

问题描述

我有一个具有可变数量注释的字符串,目标是得到

(1) 注释类型,

(2) 带注释的字符串,以及

(3) 得到没有注解的原始字符串。

例如,让我们试试 /A_RESTAURANT(汉堡王)。它位于 /A_LOCATION(芝加哥市中心)。

我能够编写正则表达式来匹配单个注释。但不知道做多个注释。

(.*)\/(A_.*)\((.*)\)(.*)

标签: regex

解决方案


这是实现目标的功能:

import re

regex = re.compile(r"/A_(?P<a_type>[^()]*)\((?P<a_string>.*?)\)")

def process(text):
    def helper(matchobject):
        annotations.append((matchobject['a_type'], matchobject['a_string']))
        return matchobject['a_string']

    annotations = []

    clean_text = regex.sub(helper, text)

    return clean_text, annotations

一个测试:

text = "Let's try /A_RESTAURANT(Burger King). It is at /A_LOCATION(DOWNTOWN Chicago)."

clean_string, annotations = process(text)

print(clean_string)
print(annotations)

输出:

Let's try Burger King. It is at DOWNTOWN Chicago.
[('RESTAURANT', 'Burger King'), ('LOCATION', 'DOWNTOWN Chicago')]

推荐阅读