Reputation: 45
I have the function:
Boolean rhyme(String words) {
Pattern pattern = Pattern.compile("...");
Matcher matcher = pattern.matcher(words);
matcher.matches();
return matcher.group(1).equals(matcher.group(2));
}
where String words
contains two words separated by a \t
like: read\tdead
.
The function is supposed to check to see if the last three letters of each word are equal, and if so returns true
, otherwise return false
.
I can't change any of the code, I'm just supposed to create the regex expression so that this functions works.
My current expression is (.{3}?)(?=[\t])|(.{3}$)
and when I plug this into regex101 it seems to work. When I use that expression in the function, I get an java.lang.IllegalStateException: No match found
error. Can anyone help me figure out where I am going wrong, and remember, I can't change any of the code except for the pattern expression.
Upvotes: 0
Views: 179
Reputation: 8044
The code is flawed unfortunately. More needs to be changed to make this work, because if there is no match (ie, words don't end with the same 3 letters) then matcher.matches()
will return false
. Continuing with the next statement will then always throw an exception as there was no match, and therefore there are no groups to access.
Working example (with tweaked regex):
boolean rhyme(String words) {
Pattern pattern = Pattern.compile(".*(.{3})(?=[\\t]).*(.{3}$)");
Matcher matcher = pattern.matcher(words);
return matcher.matches() && matcher.group(1).equals(matcher.group(2));
}
Upvotes: 2