【发布时间】:2011-11-30 09:04:12
【问题描述】:
我必须匹配文本中的所有字母数字单词。
>>> import re
>>> text = "hello world!! how are you?"
>>> final_list = re.findall(r"[a-zA-Z0-9]+", text)
>>> final_list
['hello', 'world', 'how', 'are', 'you']
>>>
这很好,但我还有几个词要否定,即不应该出现在我的最终列表中的词。
>>> negate_words = ['world', 'other', 'words']
一个不好的方法
>>> negate_str = '|'.join(negate_words)
>>> filter(lambda x: not re.match(negate_str, x), final_list)
['hello', 'how', 'are', 'you']
但如果我的第一个正则表达式模式可以更改以考虑否定这些词,我可以保存一个循环。我发现了字符的否定,但我有话要否定,我也在其他问题中发现了 regex-lookbehind,但这也无济于事。
用python re能做到吗?
更新
我的文字可以跨越几百行。此外,negate_words 列表也可能很长。
考虑到这一点,正在为此类任务使用正则表达式,首先正确吗??有什么建议吗??
【问题讨论】:
-
negate_words很多吗? -
@bitsMiz 是的,可以有很多否定词。而且文本也可以跨越几百行。
标签: python regex regex-negation