the
cat
sat
on
the
mat
Run Code Online (Sandbox Code Playgroud)
假设这些是不同的条目。正则表达式从您要搜索的内容中的任何地方排除特定字符(在本例中为“a”)是什么?
所以你会得到的点击是“那个,在,那个”
或者如果它是一个词
I like chocolate
bananas
chocolate cake
Run Code Online (Sandbox Code Playgroud)
我只想通过在任何地方排除“巧克力”这个词来显示“香蕉”
Rah*_*hul 11
您需要的是对列入黑名单的单词或字符进行负面预测。
遵循正则表达式可以满足您的期望。
正则表达式: ^(?!.*a).*$
解释:
(?!.*a) 如果字符串中的任何位置存在列入黑名单的字符,让您先行查看并丢弃匹配。
.* 如果黑名单字符不存在,则简单地从头到尾匹配整个字符串。
要将单词列入黑名单,您必须在否定前瞻断言中修改和提及单词。
正则表达式: ^(?!.*chocolate).*$
如果chocolate是像blackchocolate hotchocolate等字符串的一部分,这也将丢弃匹配。
通过添加单词边界来严格匹配单词。
正则表达式: ^(?!.*\bchocolate\b).*$
通过\b在两端添加,它将严格向前看chocolate并丢弃匹配(如果存在)。
你的问题有点含糊,最后你会有几个选择。
\b(?:(?!a)\w)+\b
# word boundary, neg. lookahead, disallowing "a",
# afterwards match as many word characters as possible
# in the end another word boundary
Run Code Online (Sandbox Code Playgroud)
^(?!.*chocolate).+
# match the start of the line, additionally a neg. lookahead looking down the line
Run Code Online (Sandbox Code Playgroud)
假设Python,也可以转移到其他语言:
sentence = "the cat sat on the mat"
words_without_a = [word for word in sentence.split() if "a" not in word]
print(words_without_a)
# ['the', 'on', 'the']
Run Code Online (Sandbox Code Playgroud)