0

I'd like some help with a regex please. Basically, i am looking for something that would match anything but something that contains the key word.

Regex should match anything that does not contain "bar"

    String i1 = "foo";
    String i2 = "foo bar";
    String i3 = "bar foo";

    Pattern p = Pattern.compile(".*\\(!(bar)\\).*");

    Matcher matcher = p.matcher(i1);
    System.out.println(matcher.matches()); // false, should be true

    matcher = p.matcher(i2);
    System.out.println(matcher.matches()); // false

    matcher = p.matcher(i3);
    System.out.println(matcher.matches()); // false

How can regex be changed to properly do the contains check?

James Raitsev
  • 92,517
  • 154
  • 335
  • 470
  • see this similar question here: http://stackoverflow.com/questions/406230/regular-expression-to-match-string-not-containing-a-word – David Kroukamp Sep 04 '12 at 19:45

2 Answers2

2
^(?:(?!bar).)*$

Is exactly what you are looking for unless I am mistaken.

endy
  • 3,872
  • 5
  • 29
  • 43
0

Couldn't you just match you keyword and negate the match? as in:

String i1 = "foo";
Pattern p = Pattern.compile(".*\\((bar)\\).*");

Matcher matcher = p.matcher(i1);
System.out.println(!matcher.matches());

Otherwise I would look about lookahead/lookbehind operators...

m4573r
  • 992
  • 7
  • 17