Search code examples
javaregex

Regular expression matching whole word OR operator


I am trying to match full word from some lines, wanted to know how to use the OR in regex, If i use only one keyword, it works fine. Example,

regex = ".*\\b" + "KEYWORD1" + "\\b.*";


String regex = ".*\\b" + "KEYWORD1|KEYWORD2|KEYWORD3" + "\\b.*";

    for (int i = start; i < end; i++) {           
        if (lines[i].matches(regex)) {
            System.out.println("Matches");
        }
    }

Solution

  • You want:

    String regex = ".*\\b(KEYWORD1|KEYWORD2|KEYWORD3)\\b.*";
    

    Originally, your regex was being evaluated like this:

    .*\bKEYWORD1
    |
    KEYWORD2
    |
    KEYWORD3\b.*
    

    But you want:

    .*\b
    (
        KEYWORD1
        |
        KEYWORD2
        |
        KEYWORD3
    )
    \b.*
    

    This cool tool can help you analyse regexes and find bugs like this one.