簡體   English   中英

在python中匹配以特定字符開頭的行塊

[英]Match a block of lines starting with a specific charecter in python

我想搜索一段文本並匹配 python 中以特定字符開頭的行 - 但一旦該規則被破壞,我想立即停止。

例如,在以下文本中:(以星號開頭)


* 第一點

* 第二點

**點二.一

* 最后一點三

但這是中間的一段文字

* 四


我想在遇到非項目符號文本時立即停止搜索。 即搜索/查找應僅返回“* 最后一點三”之前的文本。

我一直在嘗試各種正則表達式,但沒有運氣。 到目前為止我最接近的是

r'(^[*(**)].*)'

任何幫助將不勝感激。

謝謝

tjr

您可以使用以下正則表達式來獲取這些塊:

^(?:\*+[^*\n]*?\n*(?=\*))*\*+[^*\n]*?(?:\n|$)(?!\*)

演示

你是這個意思,

re.findall(r'^(?s)\\*[^\n]*(?:\n\\\*[^\n]*)*', s)

演示

如果目標只是匹配流中條件不為真的第一個點,那么表達這一點的最簡潔方法似乎是

>>> pattern = r'^(?s)\*[^\n]*(?:\n+\*[^\n]*)*'

>>> target = """* point one
...
... * point two
...
... ** point two.one
...
... * last point three
...
... But here is a text in between
...
... * four
... """
>>> m=re.search(pattern,target)
>>> m.group(0)
'* point one\n\n* point two\n\n** point two.one\n\n* last point three'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM