【问题标题】:How to match paragraphs containing a specific pattern with regex?如何将包含特定模式的段落与正则表达式匹配?
【发布时间】:2018-05-04 22:40:25
【问题描述】:

我有以下段落:

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)?

我在 S.O. 中找到了答案。

How match a paragraph using regex

这允许我匹配段落(两个空行之间的所有文本)。

但我不知道(我的正则表达式技能……有限)如何匹配包含特定模式的段落,并且只匹配那些段落。

提前感谢您的帮助

注意:这个想法是使用编辑 IOS 应用程序中的答案来折叠不包含模式的答案。

【问题讨论】:

  • 您使用哪种编程语言?首先拆分段落(在空行上)然后在其中查找 New-York 可能更容易。
  • 哪种风格的正则表达式? Python?你必须在一行中使用正则表达式吗?您链接到的答案拆分为“\n\n”。
  • @kabanus : Python
  • @Jan:我不想拆分段落:我想保留包含指定模式的整个段落,并且只保留那些段落。

标签: python regex


【解决方案1】:

如果您打算在 iOS 编辑应用程序中使用该模式,我发现您可能无法访问 Python 代码本身。

那么,我只能建议像这样的模式

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

请参阅regex demo。基本上,我们只从行首匹配(^(?m) 修饰符),我们检查是否有 New-YorkBerlin 作为整个单词(由于\b 单词边界)第一个双换行符之前的行,如果存在,则匹配这些行。

详情

  • (?m)^ - 行首
  • (?=.*(?:\r?\n(?!\r?\n).*)*?\bNew-York\b) - 一个积极的前瞻,确保在除换行符 (.*) 之外的 0+ 个字符之后的任何地方都有一个完整的单词 New-York 可选地后跟 0+ 个连续的 CRLF/LF 换行符序列,而不是另一个CRLF/LF 换行符后跟该行的其余部分
  • (?=.*(?:\r?\n(?!\r?\n).*)*?\bBerlin\b) - 一个完整的单词 Berlin 在除换行符之外的 0+ 个字符之后的任何位置 (.*) 可选地后跟 0+ 个连续的 CRLF/LF 换行符序列,而不是另一个 CRLF/LF 换行符,然后是该行的其余部分
  • .* - 匹配行
  • (?:\r?\n(?!\r?\n).*)* - 匹配 0+ 个连续出现的:
    • \r?\n(?!\r?\n) - 换行符(CRLF 或 LF)后面没有另一个 CRLF 或 LF
    • .* - 该行的其余部分。

【讨论】:

    【解决方案2】:

    使用支持空拆分的newer regex module

    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']
    

    【讨论】:

    • 1) 感谢您的回答 2) 我在 Pythonista 中尝试过(与编辑相同的开发人员;顺便说一句,编辑可以使用 Python 脚本)并遇到问题,因为 - 我认为 - 它似乎没有支持较新的正则表达式模块 3)您的回答似乎意味着没有纯正则表达式(PCRE)解决方案。
    猜你喜欢
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    相关资源
    最近更新 更多