如何删除所有重复的字符

cl-*_*l-r 3 java regex

我不喜欢使用Java工作的Regex示例来删除所有重复的字符.

此代码不能正常工作:删除'g'和'<',两个以上的字符没有明显减少为1,'454'减少为'5'.

s = "aa  hgjii2222 22    FFonn;;;,,1111111111 22< 454";
p = Pattern.compile("(.)(.)");
m = p.matcher(s);
System.out.println(m.replaceAll("$1") );
Run Code Online (Sandbox Code Playgroud)

输出:

a hji222 Fon;,11111 2 5

我尝试过其他解决方案,但收效甚微.

cod*_*ict 5

你可以做:

String s= "aa  hgjii2222 22    FFonn;;;,,1111111111 22< 454";
s = s.replaceAll("(.)\\1+","$1");
Run Code Online (Sandbox Code Playgroud)

使用的正则表达式是: (.)\\1+

(.)  - Matches any non-newline character and remembers it
\\1+ - One or more repetitions of the remembered character
Run Code Online (Sandbox Code Playgroud)