I don't think I would use a regex for this:
public static String removeRepeatedLastCharacter(String text) {
if (text.length() == 0) {
return text;
}
char lastCharacter = text.charAt(text.length() - 1);
for (int i = text.length() - 2; i >= 0; i--) {
if (text.charAt(i) != lastCharacter) {
return text.substring(0, i + 1);
}
}
return "";
}
Personally, I find this easier to understand than regular expression. It may or may not be faster - I would not want to make a prediction.
Note that this always removes the trailing character, whether it is repeated or not. This means that single character strings always end with empty strings:
"" => ""
"x" => ""
"xx" => ""
"ax" => "a"
"abcd" => "abc"
"abcdddd" => "abc"
source
share