James Raitsev
James Raitsev

Reputation: 96401

Using 'contains check' via regex

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?

Upvotes: 0

Views: 75

Answers (2)

endy
endy

Reputation: 3872

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

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

Upvotes: 2

m4573r
m4573r

Reputation: 990

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...

Upvotes: 0

Related Questions