有没有办法让正则表达式尽可能多地匹配特定单词?例如,如果我正在查找以下单词:昨天、今天、明天
我想要提取以下完整单词:
以下整个单词应该无法匹配(基本上是拼写错误):
到目前为止我能想到的最好的是:
\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?)?
-tod
或toda
或今天
tom(?:o(?:r(?:r(?:o(?:w)?)?)?)?)?
-tom
、tomo
、tomor
、tomorr
、tomorro
或明天
\b
- 尾随单词边界
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/