Negating a set of words via java regex

被刻印的时光 ゝ 提交于 2019-12-17 23:17:23

问题


I would like to negate a set of words using java regex.

Say, I want to negate cvs, svn, nvs, mvc. I wrote a regex which is ^[(svn|cvs|nvs|mvc)].

Some how that seems not to be working.


回答1:


Try this:

^(?!.*(svn|cvs|nvs|mvc)).*$

this will match text if it doesn't contain one of svn, cvs, nvs or mvc.

This is a similar question: C# Regex to match a string that doesn't contain a certain string?




回答2:


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:

!/svn|cvs|nvs|mvc/.test("this is your test string");



回答3:


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.



来源:https://stackoverflow.com/questions/1333540/negating-a-set-of-words-via-java-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!