簡體   English   中英

Python正則表達式-在子字符串中查找多個字符

[英]Python regex - Find multiple characters in a substring

print 'cycle' ;While i in range(1,n) [[print "Number:" ;print i; print 'and,']]

例如,我有這樣一條線。 我只想從雙括號內的[[...]]子字符串中提取分號字符。

如果我使用re.search(\\[\\[.*(\\s*;).*\\]\\])我只會得到一個分號。 有合適的解決方案嗎?

正則表達式從來都不是此類事情的理想選擇,因為它很容易絆倒,但是以下模式在平凡的情況下仍然有效:

;(?=(?:(?!\[\[).)*\]\])

模式細分:

;                # match literal ";"
(?=              # lookahead assertion: assert the following pattern matches:
    (?:          
        (?!\[\[) # as long as we don't find a "[["...
        .        # ...consume the next character
    )*           # ...as often as necessary
    \]\]         # until we find "]]"
)

換句話說,該模式檢查是否在分號后跟]] ,而不是[[


模式不起作用的字符串示例:

  • ; ]] ; ]] (將匹配)
  • [[ ; "this is text [[" ]] [[ ; "this is text [[" ]] (不匹配)

暫無
暫無

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

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