Josephus87
Josephus87

Reputation: 1178

Regex find word Java case insensitive

I want to find the following words in a list but I can't get my regex right in java.

Arduino,Katar,Bacardi

String keyWord = ar;
List<String> l = hubList.stream().filter(x -> x.matches("(?i)("+keyWord+")").collect(Collectors.toList();

Upvotes: 1

Views: 1831

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

To match ar inside a string (you need a whole word match with matches()!) you need to allow any symbols before and after the keyword.

Since keyword may contain (potentially) special regex characters (like ( or [), it is safer to use \Q...\E operators that indicate that the characters between them are treated as literal characters.

Thus, I suggest

x.matches("(?si).*\\Q"+keyWord+"\\E.*")

If it is not the case and there will be just letters:

x.matches("(?si).*"+keyWord+".*")

Note that I also add (?s) singleline modifier to force a . to match any character, even a newline.

Upvotes: 1

Related Questions