正则表达式如何在任何地方排除特定字符或字符串 [英] regex how to exclude specific characters or string anywhere

查看:143
本文介绍了正则表达式如何在任何地方排除特定字符或字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

the
cat
sat
on
the
mat

假设这些是不同的条目.正则表达式从您要搜索的内容中的任何地方排除特定字符(在本例中为a")是什么?

assuming those are different entries. what would the regex expression be to exclude a specific character, in this case "a", from anywhere at all in the thing you were searching for?

所以你会得到的点击是那个,在,那个"

so the hits you would get back are "the, on, the"

或者如果它是一个词,如

or if it was a word as in

I like chocolate
bananas
chocolate cake

我只希望bananas"通过在任何地方排除chocolate"这个词来显示命中

I would like only "bananas" to show a hit by excluding the word "chocolate" anywhere

推荐答案

您需要的是对列入黑名单的单词或字符进行否定前瞻.

What you need is a negative lookahead for blacklisted word or character.

遵循正则表达式可以满足您的期望.

Following regex does what you are expecting.

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

说明:

(?!.*a) 让我们向前看,如果字符串中的任何位置都存在黑名单字符,则丢弃匹配.

(?!.*a) let's you lookahead and discard matching if blacklisted character is present anywhere in the string.

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

.* simply matches whole string from beginning to end if blacklisted character is not present.

Regex101 演示

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

For blacklisting a word you will have to modify and mention word in negative lookahead assertion.

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

Regex101 演示

如果 chocolate 是字符串的一部分,例如 blackchocolate hotchocolate 等,这也会丢弃匹配.

This will also discard match if chocolate is a part of string like blackchocolate hotchocolate etc.

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

Strict matching of word by adding word boundaries.

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

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

By adding \b on both ends it will strictly lookahead for chocolate and discard match if present.

Regex101 演示

这篇关于正则表达式如何在任何地方排除特定字符或字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆