I recently had this question in an interview and came up with this solution after looking here.
String input = "First Middle Last";
Pattern p = Pattern.compile("(?<=\\s+|^)\\w");
Matcher m = p.matcher(input);
while (m.find()) {
System.out.println(m.group());
}
This regex won't pick up non-word characters at the start of strings. So if someone enters "Mike !sis Strawberry", the return will be M, S. This is not the case with the selected answer that returns M, !, S
The regex works by serching for single word characters (\w) that have one or more space characters (\s+) or are at the start of a line (^).
To modify what is being searched for, the \w can be changed to other regex valid entries.
To modify what precedes the search character, modify (\s+|^). In this example \s+ is used to look for one or more white spaces and the ^ is used to determine if the character is at the start of the string being searched. To add additional criteria, add a pipe character followed by a valid regex search entry.