匹配除指定字符串之外的所有内容 [英] Match everything except for specified strings

查看:67
本文介绍了匹配除指定字符串之外的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道以下正则表达式将匹配red"、green"或blue".

I know that the following regex will match "red", "green", or "blue".

red|green|blue

有没有一种简单的方法可以让它匹配除了几个指定字符串的所有内容?

Is there a straightforward way of making it match everything except several specified strings?

推荐答案

如果您想确保字符串既不是红色、绿色也不是蓝色,Caskey 的答案就是它.然而,通常需要的是确保线条中的任何地方都不包含红色、绿色或蓝色.为此,使用 ^ 锚定正则表达式,并在否定前瞻中包含 .* :

If you want to make sure that the string is neither red, green nor blue, caskey's answer is it. What is often wanted, however, is to make sure that the line does not contain red, green or blue anywhere in it. For that, anchor the regular expression with ^ and include .* in the negative lookahead:

^(?!.*(red|green|blue))

另外,假设您想要包含单词engine"但没有任何这些颜色的行:

Also, suppose that you want lines containing the word "engine" but without any of those colors:

^(?!.*(red|green|blue)).*engine

您可能认为可以将 .* 分解为正则表达式的头部:

You might think you can factor the .* to the head of the regular expression:

^.*(?!red|green|blue)engine     # Does not work

但你不能.您必须同时拥有 .* 的两个实例才能使其工作.

but you cannot. You have to have both instances of .* for it to work.

这篇关于匹配除指定字符串之外的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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