RonPringadi
RonPringadi

Reputation: 1494

Java regex to prevent match for specific keywords

I have been exploring negative look ahead and negative look behind. But they don't seem to do what I want.

Say I have a sentence "word1 word2 word3 word4", I need a regex that refuse a match if word3 or word7 exist in that sentence. In another word matcher.find() should be false. How do I do that?

Ideally I want the captured sentence to be as relaxed as possible .* however I only able to prevent a match if I tighten captured sentence, see (\\w{4}\\d{1}\\s.*) section below which ends up as //Result: Nothing

    String contents = null;
    contents = "word1 word2 word3 word4";
    m = Pattern.compile("(?i)(.*)").matcher(contents);
    //Result: word1 word2 word3 word4

    m = Pattern.compile("(?i)(?!.*(word3))(.*)").matcher(contents);
    //Result: ord3 word4

    m = Pattern.compile("(?i)(?!.*(word3))(\\w{4}\\d{1}\\s.*)").matcher(contents);
    //Result: Nothing

    m = Pattern.compile("(?i)(?<!(word3))(.*)").matcher(contents);
    //Result: word1 word2 word3 word4

    m = Pattern.compile("(?i)(.*)(?<!(word3))").matcher(contents);
    //Result: word1 word2 word3 word4

    m = Pattern.compile("(?i)(.*)(?<!(word4))").matcher(contents);
    //Result: word1 word2 word3 word

Upvotes: 1

Views: 529

Answers (1)

Grzegorz G&#243;rkiewicz
Grzegorz G&#243;rkiewicz

Reputation: 4586

How about:

Pattern pattern = Pattern.compile("^(?!.*(word1|word2|word3|word4|word5|word6|word7)).*$");
Matcher matcher = patter.matcher(" word1");
System.out.println(matcher.find());

This can be simplified depending on patterns in those words, e.g.:

Pattern p = Pattern.compile("^(?!.*(word[1-7])).*$");
Matcher m = p.matcher(" word8");
boolean b = m.find();

Upvotes: 1

Related Questions