正则表达式不包含一些单词 [英] Regex for not containing some words

查看:797
本文介绍了正则表达式不包含一些单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.我有一个小问题,我有一些输入文字.我只想匹配该文本,但前提是它不包含某些单词.我知道如何使用字符([^ChArAcTeRsWhItChIdOnTwAnT])做类似的事情.所以我的问题是:有什么方法可以使文本以某些单词开头和某些单词结尾,但该文本不能包含指定的单词?谢谢.

Hi all. I have small problem I have some input text. I want to match that text but only then, when it not contains some words. I know how to do similar thing with characters ([^ChArAcTeRsWhItChIdOnTwAnT]). So my question is: is there any way how to get text starting with some words and ending with some words but that text cannot contain specified word? Thanks.

推荐答案

您想要否定先行或否定先行.假设您要验证,以便短语以"string"开头,以"bee"结尾,但不包含"like".您可以使用此正则表达式(它使用负的超前查询):
You want a negative lookahead or a negative lookbehind. Suppose you want to validate so that a phrase starts with "string" and ends with "bee", but does not contain "like". You could use this regular expression (which uses a negative lookahead):
(?!.*like)^sting.*bee



如果短语包含"like",则否定的前瞻性将确保该表达式不匹配.例如,像蜜蜂一样s"将是一个匹配项,但像蜜蜂一样ting"将不匹配(因为它包含喜欢").现在,如果要同时禁止"like"和好像",则修改很简单:


The negative look ahead will ensure that the expression will not match if the phrase contains "like". For example, "sting as if a bee" would be a match, but "sting like a bee" would not match (because it contains "like"). Now, if you want to disallow both "like" and "as if", the modification is simple:

(?!.*(like|as if))^sting.*bee



现在,我上面给出的所有示例短语都不会匹配.


Now neither of the sample phrases I gave above will match.


这篇关于正则表达式不包含一些单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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