通过java正则表达式否定一组单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1333540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Negating a set of words via java regex
提问by Abhishek
I would like to negate a set of words using java regex.
我想使用 java regex 否定一组单词。
Say, I want to negate cvs
, svn
, nvs
, mvc
. I wrote a regex which is ^[(svn|cvs|nvs|mvc)]
.
说,我想否定cvs
, svn
, nvs
, mvc
。我写了一个正则表达式,它是^[(svn|cvs|nvs|mvc)]
.
Some how that seems not to be working.
一些如何这似乎不起作用。
采纳答案by Kamarey
Try this:
尝试这个:
^(?!.*(svn|cvs|nvs|mvc)).*$
this will match text if it doesn't contain one of svn, cvs, nvs or mvc.
如果文本不包含 svn、cvs、nvs 或 mvc 之一,这将匹配文本。
This is a similar question: C# Regex to match a string that doesn't contain a certain string?
这是一个类似的问题:C# Regex 匹配不包含某个字符串的字符串?
回答by RaYell
It's not that simple. If you want to negate a word you have to split it to letters and negate each letter.
没那么简单。如果你想否定一个词,你必须把它分成几个字母并否定每个字母。
so to negate
所以否定
/svn/
you have to write
你必须写
/[^s][^v][^n]/
So what you want to filter out will turn into really ugly regex and I think it's better idea to use this regex
所以你想过滤掉的东西会变成非常丑陋的正则表达式,我认为最好使用这个正则表达式
/svn|cvs|nvs|mvc/
and when you test your string against it, just negate the result.
当您针对它测试字符串时,只需否定结果即可。
In JS this would look more less like that:
在 JS 中,这看起来更不像这样:
!/svn|cvs|nvs|mvc/.test("this is your test string");
回答by pvoosten
Your regex is wrong. Between square brackets, you can put characters to require or to ignore. If you don't find ^(svn|cvs|nvs|mvc)$
, you're fine.
你的正则表达式是错误的。在方括号之间,您可以放置需要或忽略的字符。如果你没有找到^(svn|cvs|nvs|mvc)$
,你就没事。