您正在寻找的正则表达式应该包括可选组与交替。
\b(yest(?:e(?:r(?:d(?:ay?)?)?)?)?|tod(?:ay?)?|tom(?:o(?:r(?:r(?:ow?)?)?)?)?)\b
看演示
请注意,\b
单词边界非常重要,因为您只想匹配整个单词。
正则表达式解释:
\b
- 引导词边界
(yest(?:e(?:r(?:d(?:ay?)?)?)?)?|tod(?:ay?)?|tom(?:o(?:r(?:r(?:o(?:w)?)?)?)?)?)
- 捕获组匹配
yest(?:e(?:r(?:d(?:ay?)?)?)?)?
- yest
, yeste
, yester
, yesterd
,yesterda
或yesterday
tod(?:ay?)?
-tod
或toda
或today
tom(?:o(?:r(?:r(?:o(?:w)?)?)?)?)?
- tom
, tomo
, tomor
, tomorr
, tomorro
, 或tomorrow
\b
- 尾随词边界
请参阅 Python 演示:
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']