I'm trying to return a string of regular expression matches. Specifically, trying to return all vowels (aeiou) found in a string. The following code returns the 2 oo's but not the e. Expecting: eoo Getting: oo
Why is it not finding and appending the e to the StringBuilder object? Thank you.
import java.lang.StringBuilder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main {
public static void main(String[] args) {
String inp = "Hello World!";
System.out.println(vowelOnly(inp));
}
public static String vowelOnly(String input) {
Pattern vowelPattern = Pattern.compile("[aeiou]+");
Matcher vowelMatcher = vowelPattern.matcher(input);
StringBuilder sb = new StringBuilder();
int i = 0;
if (vowelMatcher.find()) {
while (vowelMatcher.find( )) {
sb.append(vowelMatcher.group());
i++;
}
return sb.toString();
} else {
return "No matches";
}
}
}
find, the one inif (vowelMatcher.find())- remove thatifand, if you really need the"No matches"return, testsbafter the loop (I would prefer returning just the empty string, since that is what the method found [message, if needed, created by caller])String, anOptional<String>, or throw an exception, but in this case, using anOptionalor throwing an exception is probably overkill.sb.append(...group())just after thatif, but code repetition isn't that good