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");
}
}
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.
The pipe character | can be used as an OR operator, which is called alternation in regex.
To get this to work properly in your example, you just need to create a group around the alternation to be sure that you are doing the OR only on the keywords you are interested in, for example:
String regex = ".*\\b(KEYWORD1|KEYWORD2|KEYWORD3)\\b.*";
What you currently have would mean .*\\bKEYWORD1 OR KEYWORD2 OR KEYWORD3\\b.*.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With