這個問題在這里已經有了答案: RegEx 獲取具有換行符的兩個字串之間的字串 2 個答案 2天前關閉。
例如,我有這樣的事情:
author - xxx
title - xxxx
abstract - xxxx
date - xxxx
author - xxx
title - xxxx
abstract - xxxx,
xxxxxxxx
xxxxxxxx
date - xxxx
我想捕捉作者和日期之間的所有內容。每次遇到這種模式時,我都會捕獲它們(沒有嵌套)。因此,所需的輸出如下所示:
["\r\nauthor...date xxx", "\r\nauthor...date xxx" ]
我遇到的困難是“作者”和“日期”之間可能存在任意行,而且我還必須注意換行符。
當我使用\r\nauthor.*\n.*\n.*\n.*date.*時,它可以讓我捕獲除“日期”之外具有“作者”四行的所有元素。但是當我嘗試通過使用來處理任意留置權時\r\nauthor((.|\r\n)*?).*date.*,它給了我一些奇怪的東西。誰能給我一些我可以用于這項任務的表達方式?謝謝!
uj5u.com熱心網友回復:
您可以re.findall與標志re.M(多行)和re.S(dotall)一起使用。這種方式.不會在換行處停止,并且^/$將匹配行的開頭和結尾(regex101):
import re
text = """author - xxx
title - xxxx
abstract - xxxx
date - xxxx
author - xxx
title - xxxx
abstract - xxxx,
xxxxxxxx
xxxxxxxx
date - xxxx"""
for group in re.findall(r"^author.*?^date.*?$", text, flags=re.M | re.S):
print(group)
print("-" * 80)
印刷:
author - xxx
title - xxxx
abstract - xxxx
date - xxxx
--------------------------------------------------------------------------------
author - xxx
title - xxxx
abstract - xxxx,
xxxxxxxx
xxxxxxxx
date - xxxx
--------------------------------------------------------------------------------
uj5u.com熱心網友回復:
我修改了我的舊答案,因為顯然不是您問題的正確答案。我的錯,我沒有正確閱讀。下一個應該適合你:
author[\w\W] ?date[^\r\n]
uj5u.com熱心網友回復:
我想必須有一個更清潔/更有效的正則運算式,但這種模式適用于全域 多行標志
^author(.|\s)*?date.*$
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/496173.html
