python正则表达式来检测一个词是否存在 [英] python regex to detect a word exists
问题描述
我想使用 python 正则表达式检测一个词是否在一个句子中.另外,希望能够否定它.
I want to detect whether a word is in a sentence using python regex. Also, want to be able to negate it.
import re
re.match(r'(?=.*\bfoo\b)', 'bar red foo here')
这段代码有效,但我不明白为什么我需要把 .*
放在那里.还要否定它,我不知道该怎么做.我试过了:
this code works but I do not understand why I need to put .*
in there.
Also to negate it, I do not know how to do that.
I've tried:
re.match(r'(?!=.*\bfoo\b)', 'bar red foo here')
但它不起作用.我的最终目标是像这样组合它们:
but it does not work. My ultimate goal is to combine them like so:
re.match(r'(?=.*\bfoo\b)(?!=.*\bbar\b)', 'bar red foo here')
推荐答案
要检测字符串中是否存在某个单词,您需要正向前瞻:
To detect if a word exists in a string you need a positive lookahead:
(?=.*\bfoo\b)
.*
是必要的,以便能够在字符串开头之外进行更远的搜索(re.match
将搜索锚定在字符串开头).
The .*
is necessary to enable searching farther than just at the string start (re.match
anchors the search at the string start).
要检查字符串中是否没有单词,请使用否定前瞻:
To check if a string has no word in it, use a negative lookahead:
(?!.*\bbar\b)
^^^
所以,将它们结合起来:
So, combining them:
re.match(r'(?=.*\bfoo\b)(?!.*\bbar\b)', input)
将在包含整个单词 foo
且不包含整个单词 bar
的字符串中找到匹配项.
will find a match in a string that contains a whole word foo
and does not contain a whole word bar
.
这篇关于python正则表达式来检测一个词是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!