且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中找到两个相邻的重复数字并用一个数字替换它们?

更新时间:2023-02-09 20:40:20

可能是 replaceAll(((\\d)\\1 +,$ 1)


  • $ 在替换字符串中扮演特殊角色,指定第一个捕获组。

  • + 允许替换尽可能多的相同数字(\\d)\\1 只能用对替换它们: 777xx => 77xx (谢谢 Ben Doom 的评论)

  • $ plays a special role in a replacing string, designating the first capturing group.
  • + allows for replacing as many identical number as possible (\\d)\\1 would only replace them by pair: 777xx => 77xx (thank you Ben Doom for the remark)

所以:

System.out.println("77433211".replaceAll("(\\d)\\1+", "$1"));

将返回

74321







String java.lang.String.replaceAll(String regex, String replacement)

替换此字符串的每个子字符串与给定的正则表达式匹配给定的替换。

Replaces each substring of this string that matches the given regular expression with the given replacement.

调用 str.replaceAll(regex,repl)形式的此方法产生的结果与表达式

An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)






警告 String.replaceAll()函数不会修改应用它的String。它返回一个修改过的字符串(或一个具有相同内容的新字符串,如果模式与任何东西不匹配)


Warning: String.replaceAll() function does not modify the String on which it is applied. It returns a modified String (or a new String with the same content if the pattern does not match anything)

所以你需要影响 replaceAll()的结果调用自身实际更新你的字符串与正则表达式更改。

So you need to affect the result of a replaceAll() call to itself to actually update your String with the regexp changes.

String aString = "77433211"
aString = aString.replaceAll("(\\d)\\1+", "$1"));