regex - 正则表达式匹配可变数量的注释
问题描述
我有一个具有可变数量注释的字符串,目标是得到
(1) 注释类型,
(2) 带注释的字符串,以及
(3) 得到没有注解的原始字符串。
例如,让我们试试 /A_RESTAURANT(汉堡王)。它位于 /A_LOCATION(芝加哥市中心)。
我能够编写正则表达式来匹配单个注释。但不知道做多个注释。
(.*)\/(A_.*)\((.*)\)(.*)
解决方案
这是实现目标的功能:
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')]
推荐阅读
- node.js - 无法解析“样式加载器”webpack 4
- alarm - AWS Cloudwatch 警报状态
- git - Git diff 通过忽略 .git 文件来复制输出
- python - 如何在 python 中取消托管在 Web URL 中的文件
- python - 将 numpy 数组转换为 pandas 数据框
- c# - C#:Type.GetType 在动态加载程序集的类上为空
- php - 在 Chart.js 图表中从 Google Analytics 加载数据
- javascript - 如何在传单杂食层上使用自定义图标?
- java - Java中的结构和数组错误
- javascript - Angular firebase 不显示密钥