Python正则表达式匹配完整或部分单词

标签 python regex substring character-class

有没有办法让正则表达式尽可能多地匹配特定单词?例如,如果我正在查找以下单词:昨天、今天、明天

我想要提取以下完整单词:

  • 是的
  • 昨天
  • 托德
  • 户田
  • 今天
  • 汤姆 明天
  • 明天

    以下整个单词应该无法匹配(基本上是拼写错误):

  • 昨天
  • 明天
  • 明天
  • 今天

    到目前为止我能想到的最好的是:

    \b((tod(a(y)?)?)|(tom(o(r(r(o(w)?)?)?)?)?)|(yest(e( r(d(a(y)?)?)?)?)?))\b (Example)

    注意:我可以使用有限状态机来实现这一点,但我认为让 regexp 来执行此操作会很愚蠢。不幸的是,我想出的任何东西都极其复杂,我希望我错过了一些东西。

  • 最佳答案

    您要查找的正则表达式应包含带有交替的可选组

    \b(yest(?:e(?:r(?:d(?:ay?)?)?)?)?|tod(?:ay?)?|tom(?:o(?:r(?:r(?:ow?)?)?)?)?)\b
    

    参见demo

    请注意\b 单词边界非常重要,因为您只想匹配整个单词。

    正则表达式解释:

    • \b - 前导字边界
    • (yest(?:e(?:r(?:d(?:ay?)?)?)?)?|tod(?:ay?)?|tom(?:o(?) :r(?:r(?:o(?:w)?)?)?)?)?) - 捕获组匹配
      • yest(?:e(?:r(?:d(?:ay?)?)?)?)? - yest, yeste 昨天昨天昨天昨天
      • tod(?:ay?)? - todtoda今天
      • tom(?:o(?:r(?:r(?:o(?:w)?)?)?)?)? - tomtomotomortomorrtomorro明天
    • \b - 尾随单词边界

    See Python demo :

    import re
    p = re.compile(ur'\b(yest(?:e(?:r(?:d(?:ay?)?)?)?)?|tod(?:ay?)?|tom(?:o(?:r(?:r(?:ow?)?)?)?)?)\b', re.IGNORECASE)
    test_str = u"yest\nyeste\nyester\nyesterd\nyesterda\nyesterday\ntod\ntoda\ntoday\ntom\ntomo\ntomor\ntomorr\ntomorro\ntomorrow\n\nyesteray\ntomorow\ntommorrow\ntody\nyesteday"
    print(p.findall(test_str))
    # => [u'yest', u'yeste', u'yester', u'yesterd', u'yesterda', u'yesterday', u'tod', u'toda', u'today', u'tom', u'tomo', u'tomor', u'tomorr', u'tomorro', u'tomorrow']
    

    关于Python正则表达式匹配完整或部分单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34541218/

    相关文章:

    r - dplyr 中的快速字符串计数

    java - 从 HashMap 中特定出现特殊字符的值中检索字符串

    python - 从其 wxPython 父级中删除一个小部件

    python - 将 Python Twisted 与多处理混合使用?

    Python copy.copy() 与 NumPy np.copy()

    regex - 正则表达式中的命名捕获

    python - pandas如何识别具有特定模式的字符串

    mysql - 没有在 Mysql 参数中获取值

    swift - 为什么带有范围的 swift 子字符串需要特殊类型的 Range

    python - 在python中更新字典