如何在Java中找到两个相邻的重复数字并用一个数字替换它们?
我需要在字符串中找到两个相邻的重复数字,并用一个替换。 如何在Java中执行此操作。 一些例子:
123345应该是12345 77433211应该是74321
可能是replaceAll("(\\d)\\1+", "$1")
-
$
在替换字符串中扮演特殊角色,指定第一个捕获组。 -
+
允许替换尽可能多的相同数字(\\d)\\1
只能用对替换它们:777xx
=>77xx
(感谢Ben Doom的评论)
所以:
System.out.println("77433211".replaceAll("(\\d)\\1+", "$1"));
将返回
74321
String java.lang.String.replaceAll(String regex, String replacement)
将给定替换的给定正则表达式匹配的此字符串的每个子字符串替换。
调用str.replaceAll(regex, repl)
forms的此方法会产生与str.replaceAll(regex, repl)
完全相同的结果
java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)
警告 : String.replaceAll()
函数不会修改应用它的String。 它返回一个修改过的String(如果模式与任何东西都不匹配,则返回一个内容相同的新String )
因此,您需要影响对自身的replaceAll()
调用的结果,以实际使用regexp更改来更新String。
String aString = "77433211" aString = aString.replaceAll("(\\d)\\1+", "$1"));
我终于自己做了。 那些正在寻找解决方案的人,我就是这样做的:
import java.util.regex.*; public class RepetingDigits{ public static void main(String[] args) { String word = "77433211"; Pattern pattern = Pattern.compile("(\\d)\\1"); Matcher matcher = pattern.matcher(word); word = matcher.replaceAll("$1"); System.out.println(word); } }
更简单:
**word = word.replaceAll("(\\d)\\1", "$1");**
使用正则表达式:
var myString='123345' myString.replace(/([0-9])\1/g,'$1')
这将恰好匹配2次重复。
'123334'.replace(/([0-9])\1+/g,'$1')
这是两个重复数字的正则表达式(x是数字)
[x]{2}(?!=[x])