簡體   English   中英

如何匹配包含特定模式的段落與正則表達式?

[英]How to match paragraphs containing a specific pattern with regex?

我有以下段落:

This is paragraph #1
New-York, London, Paris, Berlin
Some other text
End of paragraph

This is paragraph #2
London, Paris
End of paragraph

This is paragraph #3
New-York, Paris, Berlin
Some other text
End of paragraph

This is paragraph #4
End of paragraph

This is paragraph #5
Paris, Berlin
Some other text
End of paragraph

我如何使用正則表達式匹配包含例如紐約(#1和#3)或倫敦(#1,#2)的段落? 甚至是紐約和柏林(#1,#3)?

我在SO中找到了答案

如何匹配使用正則表達式的段落

這允許我匹配段落(兩個空白行之間的所有文本)。

但我無法想象(我的正則表達式技能是......有限的)如何匹配包含特定模式的段落,只有那些段落。

在此先感謝您的幫助

注意:我的想法是使用編輯IOS應用程序中的答案來折疊不包含模式的答案。

如果您計划在編輯iOS應用程序中使用該模式,我發現您可能無法訪問Python代碼本身。

然后,我所能提出的就是模式

(?m)^(?=.*(?:\r?\n(?!\r?\n).*)*?\bNew-York\b)(?=.*(?:\r?\n(?!\r?\n).*)*?\bBerlin\b).*(?:\r?\n(?!\r?\n).*)*

請參閱正則表達式演示 基本上,我們只匹配從行的開頭( ^(?m)修飾符),我們檢查是否有New-YorkBerlin作為整個單詞(由於\\b字邊界)在第一行之前的任何地方雙線中斷,如果存在,則匹配這些線。

細節

  • (?m)^ - 開始行
  • (?=.*(?:\\r?\\n(?!\\r?\\n).*)*?\\bNew-York\\b) - 一個積極的前瞻,確保New-York任何地方都有一個完整的單詞在除了換行符之外的0+個字符( .* )之后,可選地跟隨0 +連續的CRLF / LF換行符序列,而不是另一個CRLF / LF換行符,其次是換行符
  • (?=.*(?:\\r?\\n(?!\\r?\\n).*)*?\\bBerlin\\b) - 除了換行符之外的0+字符之后的任何地方Berlin的完整字詞.* )任選地跟隨0 +連續的CRLF / LF換行序列,然后沒有跟隨另一個CRLF / LF換行,接着是其余的生產線
  • .* - 匹配線
  • (?:\\r?\\n(?!\\r?\\n).*)* - 匹配連續0次以上:
    • \\r?\\n(?!\\r?\\n) - 換行符(CRLF或LF)未跟隨另一個CRLF或LF
    • .* - 其余部分。

使用支持空分割的較新的regex模塊

import regex as re

string = """
This is paragraph #1
New-York, London, Paris, Berlin
Some other text
End of paragraph

This is paragraph #2
London, Paris
End of paragraph

This is paragraph #3
New-York, Paris, Berlin
Some other text
End of paragraph

This is paragraph #4
End of paragraph

This is paragraph #5
Paris, Berlin
Some other text
End of paragraph
"""

rx = re.compile(r'^$', flags = re.MULTILINE | re.VERSION1)

needle = 'New-York'

interesting = [part 
    for part in rx.split(string)
    if needle in part]

print(interesting)
# ['\nThis is paragraph #1\nNew-York, London, Paris, Berlin\nSome other text\nEnd of paragraph\n', '\nThis is paragraph #3\nNew-York, Paris, Berlin\nSome other text\nEnd of paragraph\n']

我認為你的具體案例根本不需要正則表達式:

[i for i,p in enumerate(mystr.split('\n\n')) if 'New-York' in p or 'London' in p]

在您的情況下導致:

[0, 1, 2]

顯然and條件and條件同樣容易,或者否定if 僅當您需要段落索引時才使用enumerate 如果你想要段落本身,你不需要它。 無論如何,無需強制使用regex

暫無
暫無

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

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