Working on a Java regular expression that will match either "es" or "s" at the end of the string and return the substring without that suffix. Seems easy, but I can't get the 'e' to match with the expressions I'm trying.
Here's the output I should get:
"inches" -> "inch"
"meters" -> "meter"
"ounces" -> "ounc"
but with this regular expression:
Pattern.compile("(.+)(es|s)$", Pattern.CASE_INSENSITIVE);
I'm actually getting:
"inches" -> "inche"
After some research I discovered that the ".+" part of my search is too greedy, and changing it to this:
Pattern.compile("(.+?)(es|s)$", Pattern.CASE_INSENSITIVE);
fixes the problem. My question, though, is why did the 's' match at all? If the 'greedy' nature of the algorithm was the problem, shouldn't it have matched the whole string?