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.

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
Abhishek
  • 6,862
  • 22
  • 62
  • 79
  • 1
    Possible duplicate: http://stackoverflow.com/questions/42990/regex-to-match-against-something-that-is-not-a-specific-substring – finnw Aug 26 '09 at 10:10
  • 2
    Also see: http://stackoverflow.com/questions/406230/regular-expression-to-match-string-not-containing-a-word – finnw Aug 26 '09 at 10:11
  • 1
    ...and http://stackoverflow.com/questions/717644/regular-expression-that-doesnt-contain-certain-string – finnw Aug 26 '09 at 10:26
  • 1
    This kind of question appears quite often so I think it deserves a tag. I've added one called "regex-negation". – finnw Aug 26 '09 at 10:28

3 Answers3

52

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?

Community
  • 1
  • 1
Kamarey
  • 10,832
  • 7
  • 57
  • 70
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");
RaYell
  • 69,610
  • 20
  • 126
  • 152
  • that's probably not correct, because you don't match the beginning ^ and the end $ of the string – pvoosten Aug 26 '09 at 09:57
  • 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 Aug 26 '09 at 10:18
2

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.

Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
pvoosten
  • 3,247
  • 27
  • 43
  • that actually not helpful as this is not purely regex. if you don't have to option to change code, this won't solve the QAs issue. – Alexander Oh Feb 09 '16 at 16:00