How to split based on keywords in regex, then whitespace in Java?

Viewed 28

I would like to split a string based on three factors.

  1. Regex is case insensitive

  2. If the string contains any of the terms "Red hot", "Ice cold", "Warm" or "Mild" So for example if the string is "Red hot Ice cold", when I run .split(regex) on the string, I should get an array with "Red hot" and "Ice cold" as two separate entries.

  3. If the string does not match any of the terms, it should then split based on whitespace. So for example if the string is "Red Ice", it should split into an array containing "Red" and "Ice". It currently splits into "Red Ice" as one entry in the array. If the string is "Red hot Ice cold red", it should split into an array containing "Red hot", "Ice cold" and "red". It currently splits into "Red hot" and "Ice cold red".

So far the regex I have is "(?i)\s(?=("Red hot"|"Ice cold"|"Warm"|"Mild"))"

How do I add the criteria that if none of the terms match, it should split on white space? I don't understand how to add priority to the regex. Thanks all!

1 Answers

I would suggest a regex pattern matching approach which puts the multi-word terms first in an alternation, followed by all other single word terms:

String input = "I at some red hot not mild food and drank an ice cold Coke";
Pattern r = Pattern.compile("(?i)\\b(?:Red hot|Ice cold|\\w+)\\b");
Matcher m = r.matcher(input);
List<String> matches = new ArrayList<>();
while (m.find()) {
    matches.add(m.group());
}
System.out.println(matches);

This prints:

[I, at, some, red hot, not, mild, food, and, drank, an, ice cold, Coke]

Note that because Warm and Mild are individual words, your default split on whitespace behavior should already be including them.

Related