正则表达式如何在任何地方排除特定字符或字符串

you*_*now 1 regex

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) 如果字符串中的任何位置存在列入黑名单的字符,让您先行查看并丢弃匹配。

.* 如果黑名单字符不存在,则简单地从头到尾匹配整个字符串。

Regex101 Demo


要将单词列入黑名单,您必须在否定前瞻断言中修改和提及单词。

正则表达式: ^(?!.*chocolate).*$

Regex101 Demo

如果chocolate是像blackchocolate hotchocolate等字符串的一部分,这也将丢弃匹配。


通过添加单词边界来严格匹配单词。

正则表达式: ^(?!.*\bchocolate\b).*$

通过\b在两端添加,它将严格向前看chocolate并丢弃匹配(如果存在)。

Regex101 Demo


Jan*_*Jan 8

你的问题有点含糊,最后你会有几个选择。

第一个正则表达式解决方案(不允许单词中出现字符):

\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)

请参阅regex101.com 上的演示


第二个正则表达式解决方案(不允许使用完整的单词):

^(?!.*chocolate).+
# match the start of the line, additionally a neg. lookahead looking down the line
Run Code Online (Sandbox Code Playgroud)

请参阅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']
Run Code Online (Sandbox Code Playgroud)