我不会使用正则表达式:
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 的“规格”:
请注意,这只会删除最后重复的字符。这意味着不会触及单个字符串,但如果两个字符相同,则两个字符串可能会变为空:
"" => ""
"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"