Python 匹配完整或部分单词的正则表达式
Python regexp to match full or partial word
有没有办法让正则表达式匹配尽可能多的特定单词?例如,如果我要查找以下词:昨天、今天、明天
我要提取以下完整单词:
是的
昨天
今天
户田
今天
汤姆
明天
明天
以下整个单词应该无法匹配(基本上是拼写错误):
昨天
明天
明天
大家
到目前为止我能想到的最好的是:
\b((tod(a(y)?)?)|(tom(o(r(r(o(w)?)?)?)?)?)|(yest(e(r(d(a(y)?)?)?)?)?))\b
(Example)
注意:我可以使用有限状态机来实现这一点,但我认为让正则表达式来执行此操作会让人发笑。不幸的是,我想出的任何东西都非常复杂,我希望我只是错过了一些东西。
管道分隔所有有效的单词或单词子字符串,如下所示。这将只匹配所需的有效拼写
^(?|yest|yesterday|tod|today)\b
对此进行了测试
您正在寻找的正则表达式应该包括带有交替的可选组。
\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
、yester
、yesterd
、yesterda
或 yesterday
tod(?:ay?)?
- tod
或 toda
或 today
tom(?:o(?:r(?:r(?:o(?:w)?)?)?)?)?
- tom
、tomo
、tomor
、tomorr
、tomorro
或 tomorrow
\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']
有没有办法让正则表达式匹配尽可能多的特定单词?例如,如果我要查找以下词:昨天、今天、明天
我要提取以下完整单词:
以下整个单词应该无法匹配(基本上是拼写错误):
到目前为止我能想到的最好的是:
\b((tod(a(y)?)?)|(tom(o(r(r(o(w)?)?)?)?)?)|(yest(e(r(d(a(y)?)?)?)?)?))\b
(Example)
注意:我可以使用有限状态机来实现这一点,但我认为让正则表达式来执行此操作会让人发笑。不幸的是,我想出的任何东西都非常复杂,我希望我只是错过了一些东西。
管道分隔所有有效的单词或单词子字符串,如下所示。这将只匹配所需的有效拼写
^(?|yest|yesterday|tod|today)\b
对此进行了测试
您正在寻找的正则表达式应该包括带有交替的可选组。
\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
、yester
、yesterd
、yesterda
或yesterday
tod(?:ay?)?
-tod
或toda
或today
tom(?:o(?:r(?:r(?:o(?:w)?)?)?)?)?
-tom
、tomo
、tomor
、tomorr
、tomorro
或tomorrow
\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']