我正在尝试在Python中使用正则表达式从文本中捕获整个单词。这很简单,但我也想删除撇号指示的收缩和所有格。
目前我有(?iu)(?<!')(?!n')[w]+
对以下文本进行测试
一棵树还是多棵树?我的树是绿色的。我还没想通。
给出这些匹配项
一棵树或多棵树 我的树绿了 我还没想通
在此示例中,负后视可防止撇号后的"s"和"t"作为整个单词进行匹配。但是我如何写负面的前瞻(?!n')
以便匹配项包含"did"而不是"didn"?
(我的用例是一个简单的 Python 拼写检查器,每个单词都会被验证拼写是否正确。我最终使用了自动更正模块,因为 pyenchant、aspell-python 和其他模块在通过 pip 安装时不起作用(
我会使用这个正则表达式:
(?<![w'])w+?(?=b|n't)
这将匹配单词字符,直到遇到n't
。
结果:
>>> re.findall(r"(?<![w'])w+?(?=b|n't)", "One tree or many trees? My tree's green. I didn't figure this out yet.")
['One', 'tree', 'or', 'many', 'trees', 'My', 'tree', 'green', 'I', 'did', 'figure', 'this', 'out', 'yet']
故障:
(?<! # negative lookbehind: assert the text is not preceded by...
[w'] # ... a word character or apostrophe
)
w+? # match word characters, as few as necessary, until...
(?=
b # ... a word boundary...
| # ... or ...
n't # ... the text "n't"
)