我有下面的文本塊,我試圖用正則運算式分成 3 個塊。當您看到名稱欄位時,它將開始一個新塊。如何回傳所有 3 個塊?
name: marvin
attribute: one
day: monday
dayalt: test << this is a field that can sometimes show up
name: judy
attribute: two
day: tuesday
name: dot
attribute: three
day: wednesday
import re
lines = """name: marvin
attribute: one
day: monday
dayalt: test << this is a field that can sometimes show up
name: judy
attribute: two
day: tuesday
name: dot
attribute: three
day: wednesday
"""
a=re.findall("(name.*)[\n\S\s]", lines, re.MULTILINE)
Block1 將回傳為 "name: marvin\nattribute: one\nday: monday\ndayalt: test
謝謝!
uj5u.com熱心網友回復:
下面的情況如何,它使用積極的前瞻:
import re
lines = """name: marvin
attribute: one
day: monday
dayalt: test
name: judy
attribute: two
day: tuesday
name: dot
attribute: three
day: wednesday"""
blocks = re.findall(r"name: .*?(?=name: |$)", lines, re.DOTALL)
print(blocks)
# ['name: marvin\nattribute: one\nday: monday\ndayalt: test\n',
# 'name: judy\nattribute: two\nday: tuesday\n',
# 'name: dot\nattribute: three\nday: wednesday']
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473895.html
上一篇:如何顯示某些影像雙寬的影像串列
