我正在用Python学习正则表达式,我想准备一个RE来匹配和收集下面输入的句子:
我的预期输出应该给我类别,项目和该项目的描述。因此,对于第一项,蛋糕,RE应该分组“食物”,“蛋糕”,“烤甜食品由面粉,糖和其他成分。”
我现在的RE是这样的:
[0-9]+\s*.\s*(\w*)\s*:\s*(\w*)\s*:\s*(.*)这似乎是工作的项目,有描述,没有换行。如果它有一个换行符,即示例中的计算机,则RE只与其描述匹配,直到行中断为止。RE抛弃了描述中的第二句。
请帮助我理解我在这里错过了什么。
发布于 2020-09-14 08:08:29
这可能是一种基本的方法,但它适用于您提供的示例输入:
[0-9]+\s*.\s*(\w*)\s*:\s*(\w*)\s*:\s*((?:.*[\n\r]?)+?)(?=$|\d\s*\.)
基本上,我们在描述中尽可能多地接受文本(包括换行符),直到我们到达文件的末尾或另一个数字索引。
您可以看到实现这里
发布于 2020-09-14 08:02:58
如果类别、项和描述用双换行符分隔,则可以使用此示例解析它(regex101):
import re
txt = '''1. Food : Cake : Baked sweet food made from flour, sugar and other ingredients.
2. Electronics : Computer : A machine to carry out a computer programming operation.
Computers mainly consists of a CPU, monitor, keyboard and a mouse.
3. Automobile : Car : Car is a four wheeled motor vehicle used for transportation.'''
for cat, item, desc in re.findall(r'^(?:\d+)\.([^:]+):([^:]+):(.*?)(?:\n\n|\Z)', txt, flags=re.M|re.S):
print(cat)
print(item)
print(desc)
print('-' * 80)指纹:
Food
Cake
Baked sweet food made from flour, sugar and other ingredients.
--------------------------------------------------------------------------------
Electronics
Computer
A machine to carry out a computer programming operation.
Computers mainly consists of a CPU, monitor, keyboard and a mouse.
--------------------------------------------------------------------------------
Automobile
Car
Car is a four wheeled motor vehicle used for transportation.
--------------------------------------------------------------------------------https://stackoverflow.com/questions/63880133
复制相似问题