【问题标题】:Multiple matches separated by arbitrary text由任意文本分隔的多个匹配项
【发布时间】:2014-08-19 15:17:08
【问题描述】:

我正在尝试编写一个正则表达式,它将匹配由任意字符串分隔的相同主题标签。所以

Lorem Ipsum #molecule 只是打印和排版的虚拟文本 行业。 Lorem Ipsum #Molecule 一直是业界标准的虚拟文本 自 1500 年代以来,当一位不知名的印刷商采用了一种类型的厨房和 把它炒作了一本类型标本书##Molecule。它不仅活了下来 五个世纪,也是电子排版的飞跃, 基本保持不变。它在 1960 年代流行于 @Molecule 包含 Lorem Ipsum 段落的 Letraset 表的发布,以及 最近使用 Aldus PageMaker 等桌面排版软件 包括 Lorem Ipsum 的版本。

我该怎么做?这个正则表达式(\#[Mm]olecule) 显然不起作用。

【问题讨论】:

    标签: python regex


    【解决方案1】:

    您可以尝试([#@]+[Mm]olecule) 正则表达式,无需转义# 并在索引1 处获取匹配组。

    这是regex101上的演示

    输出:

    MATCH 1
    1.  [12-21]     `#molecule`
    MATCH 2
    1.  [101-110]   `#Molecule`
    MATCH 3
    1.  [265-275]   `##Molecule`
    MATCH 4
    1.  [450-459]   `@Molecule`
    

    这里是直接来自regex101 站点的忽略大小写的示例代码。

    import re
    p = re.compile(ur'([#@]+molecule)', re.IGNORECASE)
    test_str = ...
    
    re.findall(p, test_str)
    

    【讨论】:

    • 是的,就是这样。谢谢。
    • 不知道您为什么删除了赛后分组。我希望所有匹配的主题标签都像您第一次那样组合成一个。
    • 赛后分组是什么意思?
    • 用示例代码试试。如果它不起作用,请告诉我,我会再次更新它。
    • @hwnd 原来的正则表达式是/([#@]+[Mm]olecule)/g,这正是我想要的,基本上是对该模式的所有匹配的前瞻。
    【解决方案2】:

    使用Character Class 匹配其中任一字符。

    >>> re.findall(r'[#@]+(?i)molecule', data)
    ['#molecule', '#Molecule', '##Molecule', '@Molecule']
    

    注意:使用inline (?i) modifier 启用不区分大小写的匹配。

    【讨论】:

    • 不匹配两个hastag版本##Molecule
    • @dawg 错字,已修复。谢谢
    • 是的,你和@Braj 说得对,但副作用不同,让我看看我的口袋里是否有一些 +1。 :)
    【解决方案3】:
    s="""
    Lorem Ipsum #molecule is simply dummy text of the printing and typesetting industry.    Lorem Ipsum has #Molecule been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book ##Molecule. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of @Molecule Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    """
    
    
    print re.findall("@+molecule|#+molecule",s,re.IGNORECASE)
    ['#molecule', '#Molecule', '##Molecule', '@Molecule']
    

    【讨论】:

    • 这匹配任何主题标签;他说了同样的标签。
    猜你喜欢
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多