用于识别和提取结构化信息的正则表达式

Regex to identify and extract structured information

提问人:Robert Cheatham 提问时间:9/30/2023 最后编辑:Robert Cheatham 更新时间:9/30/2023 访问量:62

问:

我正在解析一个包含结构化信息位的非结构化文本文件。编写正则表达式来识别和提取结构化字符串非常简单。似乎还应该有一种简单的方法来使用正则表达式从字符串中提取信息的各个组成部分

这是我正在做的事情的一个简化示例:

信息结构:

Integer1 - Phrase1 (Phrase2) (Integer2)

我能够建立一个正则表达式来识别该结构。这似乎有效(即使它不是最佳正则表达式模式):

import re

white='\s' # whitespace
integer='\d+'
paren_integer = '\(' + integer + '\)' # integer contained within parentheses
phrase = '.+' # one or more words
paren_phrase = '\(.+\)' # one or more words contained within parentheses
dash = '-'

exp = re.compile(integer + white + dash + white+ phrase + white + paren_phrase + white + paren_integer)
structured_string = exp.match(string_to_search)

print(structured_string)
# 'Integer1 - Phrase1 (Phrase2) (Integer2)'

一旦我确定了结构化字符串,我当然可以编写一些代码来解析和提取结构化字符串中的信息,但似乎应该有一种更简单的方法来使用正则表达式的组件,也许是通过传递列表中的正则表达式组件而不是连接的正则表达式字符串。类似于以下内容:

regex_components = [integer, white, dash, white, phrase, white, paren_phrase, white, paren_integer]
exp = re.compile(regex_components)
data_components = exp.match(string_to_search)

print(data_components)
# [Integer1, ' ', '-', ' ', Phrase1, ' ', (Phrase2), ' ', (Integer2)]

这可能吗?有没有更聪明的方法可以做到这一点?

Python 正则表达式 解析

评论

0赞 AdrianHHH 9/30/2023
这回答了你的问题吗?参考 - 这个正则表达式是什么意思?
0赞 Robert Cheatham 10/2/2023
@AdrianHHH感谢您的建议,但这无济于事。我对正则表达式的了解太基础了,以至于我没有意识到“捕获”组是我正在寻找的。我通读的教程要么掩盖了小组,要么解释被埋没了。再次感谢您的帮助!

答:

1赞 Bharel 9/30/2023 #1

您可以像这样轻松地与组 () 匹配:()

import re
compiled_re = re.compile(r"(\d+) - ([^(]+) \(([^)]+)\) (\d+)")
result = compiled_re.findall("1234 - Lesson 1 (date 1/1/2018) 5678")
print(result)  # [('1234', 'Lesson 1', 'date 1/1/2018', '5678')]

我还提高了正则表达式的效率,以防止指数回溯。