私は正規表現を使用しません:
public class Test {
public void test() {
System.out.println(removeTrailingDupes("abcdaaaaefghaaaaaaaaa"));
System.out.println(removeTrailingDupes("012003400000000"));
System.out.println(removeTrailingDupes("0120034000000001"));
System.out.println(removeTrailingDupes("cc"));
System.out.println(removeTrailingDupes("c"));
}
private String removeTrailingDupes(String s) {
// Is there a dupe?
int l = s.length();
if (l > 1 && s.charAt(l - 1) == s.charAt(l - 2)) {
// Where to cut.
int cut = l - 2;
// What to cut.
char c = s.charAt(cut);
while (cut > 0 && s.charAt(cut - 1) == c) {
// Cut that one too.
cut -= 1;
}
// Cut off the repeats.
return s.substring(0, cut);
}
// Return it untouched.
return s;
}
public static void main(String args[]) {
new Test().test();
}
}
@JonSkeet の「仕様」に合わせるには:
これにより、最後に重複した文字のみが削除されることに注意してください。つまり、1 文字の文字列は変更されませんが、2 文字の文字列は両方の文字が同じ場合は空になる可能性があります。
"" => ""
"x" => "x"
"xx" => ""
"aaaa" => ""
"ax" => "ax"
"abcd" => "abcd"
"abcdddd" => "abc"
正規表現でそのレベルの制御を達成できるのだろうか?
...の結果として追加されましたが、たとえば aaaa でこの正規表現を使用すると、何も返されません。aaaa を返す必要があります。コメント:
代わりに、次を使用します。
private String removeTrailingDupes(String s) {
// Is there a dupe?
int l = s.length();
if (l > 1 && s.charAt(l - 1) == s.charAt(l - 2)) {
// Where to cut.
int cut = l - 2;
// What to cut.
char c = s.charAt(cut);
while (cut > 0 && s.charAt(cut - 1) == c) {
// Cut that one too.
cut -= 1;
}
// Cut off the repeats.
return cut > 0 ? s.substring(0, cut): s;
}
// Return it untouched.
return s;
}
契約を結んでいる:
"" => ""
"x" => "x"
"xx" => "xx"
"aaaa" => "aaaa"
"ax" => "ax"
"abcd" => "abcd"
"abcdddd" => "abc"