【问题标题】:Regex to match repeated (unknown) substrings正则表达式匹配重复(未知)子字符串
【发布时间】:2016-02-15 19:29:55
【问题描述】:

我试图在用户消息中找到“笑声”或类似的词,例如 hahahahihihihueheu。我目前的做法如下:

>>> substring_list = ['ha', 'ah', 'he', 'eh', 'hi', 'ih', 'ho', 'hu', 'hue']
>>> pattern_core = '|'.join(substring_list)
>>> self.regex_pattern = re.compile(r'\b[a-z]*(' + pattern_core + r'){2,}[a-z]*\b', re.IGNORECASE)

[a-z]* 允许在拼写错误方面留有余地(例如,ahhahah)。原则上,这工作得相当好。问题在于它需要在substring_list 需要更新以匹配新形式的“笑声”的意义上进行维护(例如,添加xi);各国之间的“笑声”似乎差异很大。

现在我想知道是否可以在不知道单个模式的情况下以某种方式根据重复模式(大小为 2-4)找到单词。例如,hurrhurr 包含 hurr 作为重复模式。在理想情况下,我可以 (a) 匹配 hurrhurr 并 (b) 识别核心模式 hurr。我不知道这是否可以使用正则表达式。

【问题讨论】:

  • 您的 substring_list 当前匹配 hurrhurr,因为 hu 已经定义。
  • @l'L'l 注意到有一个 {2,} 量词重复该组。
  • @Mariano:我应该注意什么?
  • @l'L'l 它不会匹配 hurrhurr 因为hu 不会连续重复 2 次以上
  • 据我所知,接受的答案过于复杂,与不应该匹配的内容相匹配,并且没有提供所需的输出。

标签: python arrays regex


【解决方案1】:

这个正则表达式会做到这一点:

\b[a-z]*?([a-z]{2,}?)\1+[a-z]*?\b

用法:

self.regex_pattern = re.compile(r'\b[a-z]*?([a-z]{2,}?)\1+[a-z]*?\b', re.IGNORECASE)

Here's a working demo.

要点与您所做的相似,但“核心”不同。正则表达式的核心是这一块:

([a-z]{2,}?)\1+

逻辑是找到一个由 2 个或多个字母组成的组,然后再匹配同一组 (\1) 一次或多次。

【讨论】:

  • 艾德,这很好用! \1 指代一个组的概念是我缺少的部分。我现在如何使用它来提取重复的模式'hurr'?就像“找到重复的模式,并返回第一次出现”。
  • @Christian 使用re.findall,然后访问结果,如results = re.findall(pattern, string, re.IGNORECASE) print(results)。这是一个演示:ideone.com/nCxPj1
  • @bobblebubble 好点。那是我正在玩的其他东西的结转。固定!
【解决方案2】:

在理想情况下,我可以 (a) 匹配 hurrhurr 并且 (b) 识别核心 模式快点。我不知道这是否可以使用正则表达式。

import re

string = """hahaha, huehue, heehee, 
            axaxaxax, x the theme, ------, hhxhhxhhx, 
            bananas, if I imagine, HahHaH"""

pattern = r"""
    (
        \b               #Match a word boundary...

        ( 
            [a-z]{2,}?   #Followed by a letter, 2 or more times, non-greedy...
        )                #Captured in group 2,        

        \2+              #Followed by whatever matched group 2, one or more times...

        \b               #Followed by a word boundary.
    )                    #Capture in group 1.
"""

results = re.findall(pattern, string, re.X|re.I)
print(results)

--output:--
[('hahaha', 'ha'), ('huehue', 'hue'), ('heehee', 'hee'), ('axaxaxax', 'ax'), ('hhxhhxhhx', 'hhx'), ('HahHaH', 'Hah')]

【讨论】:

  • 这将不匹配,例如 heeheehurrhurr。但是,它将匹配 if I imaginebananas。这似乎是错误的。 regex101.com/r/qY4vP2/1
  • @Mariano,是的,会的。
  • @7stud 我看到你已经修改了正则表达式,但它仍然匹配if I imaginebananas(或者,正如马里亚诺所说,-------x the theme)。见ideone.com/FKKiRT
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 2012-03-02
  • 2017-11-09
相关资源
最近更新 更多