the
cat
sat
on
the
mat
假设这些是不同的条目。 正则表达式从您要搜索的事物中的任何位置排除特定字符(在本例中为"a")是什么?
所以你会得到的点击是"the,on,the">
或者如果它是一个词,如
I like chocolate
bananas
chocolate cake
我只想通过排除任何地方的"巧克力"一词来显示"香蕉"的热门
您需要的是对列入黑名单的单词或字符进行负面展望。
遵循正则表达式可以满足您的期望。
正则表达式:^(?!.*a).*$
解释:
(?!.*a)
让我们向前看一下,如果字符串中的任何位置存在列入黑名单的字符,则放弃匹配。
如果不存在列入黑名单的字符,.*
只是从头到尾匹配整个字符串。
正则表达式 101 演示
要将单词列入黑名单,您必须在否定的前瞻断言中修改和提及单词。
正则表达式:^(?!.*chocolate).*$
正则表达式 101 演示
如果chocolate
是黑巧克力热巧克力等字符串的一部分,这也将丢弃匹配。
通过添加单词边界来严格匹配单词。
正则表达式:^(?!.*bchocolateb).*$
通过在两端添加b
,它将严格预测chocolate
并丢弃匹配(如果存在)。
正则表达式 101 演示
你的问题措辞有点模糊,最后你有几个选择。
第一个正则表达式解决方案(不允许单词中的字符):
b(?:(?!a)w)+b
# word boundary, neg. lookahead, disallowing "a",
# afterwards match as many word characters as possible
# in the end another word boundary
观看有关 regex101.com 的演示。
第二个正则表达式解决方案(不允许完整的单词):
^(?!.*chocolate).+
# match the start of the line, additionally a neg. lookahead looking down the line
在regex101.com 上观看另一个演示。
编程:
假设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']