【发布时间】:2021-12-12 19:40:33
【问题描述】:
在文本文件中
1. Notice
Some text
End Notice
2. Blabla
Some other text
Even more text
3. Notice
Some more text
End Notice
我想用正则表达式从“2. Blabla”和以下文本(行)中提取文本。
“2. Blabla”的部分可能在纺织品中出现多次(如“1. Notice”等)。
我试过了
pattern = r"(\d+\. Blabla[\S\n\t\v ]*?\d+\. )"
re.compile(pattern)
result = re.findall(pattern, text)
print(result)
但它给了我
['2. BlaBla\nSome other text\nEven more text\n3. ']
我怎样才能摆脱“3.”?
【问题讨论】:
-
您可以使用
\d+\. Blabla[\S\s]*?(?=^\d+\. )。演示:regex101.com/r/VWLoMW/1 -
实际上,
(?m)^\d+\. Blabla[\S\s]*?(?=^\d+\. |\Z)可能是更好的选择,或者(?m)^\d+\. Blabla.*(?:\n(?!\d+\.).*)*更快。