查找与正则表达式*不*匹配的所有单词/子字符串?

2024-06-30 15:39:48 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想找到字符串中所有不在正则表达式中的部分

假设我有一个regexr'foo|bar'和一个字符串'Hello foo how are you bar',除了regex匹配的单词之外,我怎么能得到每个单词,让它返回['Hello', 'how', 'are', 'you']


Tags: 字符串youhellofoobar单词areregex
3条回答

这应该做到:

\b(?!Foo\b|bar\b)[A-Za-z]+

Demo

我们有:

\b         # match a word break
(?!        # begin a negative lookahead
  Foo\b    # match 'Foo' followed by a word break
  |        # or
  bar\b    # match 'bar' followed by a word break
)          # end negative lookahead
[A-Za-z]+  # match 1+ letters

与@dawg的答案非常相似。但在正则表达式中可以有消极的展望

st='Hello foo how are you bar'
[w for w in st.split() if re.search(r'^(?!(foo|bar))', w)] # ['Hello', 'how', 'are', 'you']

您可以使用列表理解并否定正则表达式匹配:

>>> st='Hello foo how are you bar'
>>> [w for w in st.split() if not re.search(r'foo|bar', w)]
['Hello', 'how', 'are', 'you']

您没有询问,但您可能希望在正则表达式中使用anchors,这样,如果列表中有foofoobarfoofooblulator,它将按照您的预期进行处理

如果您只需要简单的单词查找,而不需要正则表达式,那么同样的方法也适用:

>>> [w for w in st.split() if w not in {'foo', 'bar'}]
['Hello', 'how', 'are', 'you']

相关问题 更多 >