views:

1493

answers:

5

Hi folks,

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. Could you please help? Thanks.

.\J

A: 

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");
RaYell
that's probably not correct, because you don't match the beginning ^ and the end $ of the string
lbp
Well, I'm searching for any of the words on any position in a test string. If you want to match only the whole words then ^ at the beginning and $ at the end will do the trick.
RaYell
+2  A: 

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.

lbp
A: 

[(foo|bar)] means "an opening parenthesis, f, o, |, b, a, r or closing parenthesis". ^[(foo|bar)] means the same but it has to be at the beginning of the string. I suppose you meant to put the ^ inside the [], but that would only negate the character set, it would not change that it's about characters, not words.

You can't negate a set of words. The best you can do to get what you want is use svn|cvs|nvs|mvc and then check that the regex does not match (or use negative lookahead if it's part of a larger regex).

sepp2k
Ok! I made a regex as (?!(svn|cvs|nvs|mvc))\S*. This does not match even svntest, but it should be matching svntest right??
Abhishek
+2  A: 

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: http://stackoverflow.com/questions/1318279/c-regex-to-match-a-string-that-doesnt-contain-a-certain-string

Kamarey
A: 

You shouldn't negate inside the regexp. Just use simple java negation with !.

Just use

!string.matches("(svn|cvs|nvs|mvc)")

or possibly

!Pattern.compile("(svn|cvs|nvs|mvc)").matcher(input).find()

Much simpler.

Christoffer Hammarström