2024-06-30 15:39:48 发布
网友
所以我想找到字符串中所有不在正则表达式中的部分
假设我有一个regexr'foo|bar'和一个字符串'Hello foo how are you bar',除了regex匹配的单词之外,我怎么能得到每个单词,让它返回['Hello', 'how', 'are', 'you']
r'foo|bar'
'Hello foo how are you bar'
['Hello', 'how', 'are', 'you']
这应该做到:
\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,这样,如果列表中有foofoo或barfoo或fooblulator,它将按照您的预期进行处理
foofoo
barfoo
fooblulator
如果您只需要简单的单词查找,而不需要正则表达式,那么同样的方法也适用:
>>> [w for w in st.split() if w not in {'foo', 'bar'}] ['Hello', 'how', 'are', 'you']
这应该做到:
Demo
我们有:
与@dawg的答案非常相似。但在正则表达式中可以有消极的展望
您可以使用列表理解并否定正则表达式匹配:
您没有询问,但您可能希望在正则表达式中使用anchors,这样,如果列表中有
foofoo
或barfoo
或fooblulator
,它将按照您的预期进行处理如果您只需要简单的单词查找,而不需要正则表达式,那么同样的方法也适用:
相关问题 更多 >
编程相关推荐