簡體   English   中英

正則表達式在嵌套括號之間查找文本

[英]Regex to find texts between nested parenthesis

我的字符串很長,里面有嵌套循環。 我想在其中提取一個模式。

String_Text:

some random texts......
........................
........................
{{info .................
.....texts..............
...{{ some text }}...... // nested parenthesis 1
........................
...{{ some text }}...... // nested parenthesis 2
........................
}} // End of topmost parenthesis
........................
..again some random text
........................
........................ // can also contain {{  }}
......End of string.

我想提取最上括號之間的所有文本,即

Extracted_string:

info .................
.....texts..............
...{{ some text }}...... // nested parenthesis 1
........................
...{{ some text }}...... // nested parenthesis 2
........................

圖案:

1.)以{開頭,后跟任意數量的{

2.)之后,可以有任意數量的空白

3.)之后的第一個詞肯定是info

4.)取出直到未關閉此支架。

到目前為止已經嘗試了什么:

re.findall(r'\\{+[^\\S\\r\\n]*info\\s*(.*(?:\\r?\\n.*)*)\\}+')

我知道這是錯誤的,因為這樣做是在字符串中找到}的最后一個實例。 有人可以幫我提取這些括號之間的文字嗎? TIA

您需要使用遞歸方法:

{
    ((?:[^{}]|(?R))*)
}

僅更新的regex模塊支持此功能,請參見regex101.com上的演示

變通方法可以是與以{{info開頭的行匹配,然后再匹配盡可能多的0+個字符,直到僅帶有}}的行的模式:

re.findall(r'(?sm)^{{[^\S\r\n]*info\s*(.*?)^}}$', s)

參見regex演示

細節

  • (?sm) re.DOTALL (現在, .匹配換行符)和re.MULTILINE^現在匹配行開頭, $匹配行結束位置)標志
  • ^ -一行的開始
  • {{ - {{子字符串
  • [^\\S\\r\\n]* -0+個水平空格
  • info -子字符串
  • \\s* -0+空格
  • (.*?) -組1:任意0個以上的字符,並盡可能少
  • ^}}$ -行首, }}和行尾。

這個答案解釋了如何使用遞歸來實現(盡管是圓括號,但是很容易適應),但是,就我個人而言,我只是使用while循環來編寫它:

b = 1
i = si = s.index('{')
i += 1
while b:
    if s[i] == '{': b += 1
    elif s[i] == '}': b -=1
    i += 1

ss = s[si:i]

其中,將您的字符串定義為: s ,將子字符串ss賦予為:

>>> print(ss)
{{info .................
.....texts..............
...{{ some text }}...... // nested parenthesis 1
........................
...{{ some text }}...... // nested parenthesis 2
........................
}}

暫無
暫無

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

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