如何在Java中找到两个相邻的重复数字并用一个数字替换它们? [英] How to find two adjacent repeating digits and replace them with a single digit in Java?

查看:77
本文介绍了如何在Java中找到两个相邻的重复数字并用一个数字替换它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在字符串中找到两个相邻的重复数字,并用一个替换。如何在Java中执行此操作。一些例子:

I need to find two adjacent repeating digits in a string and replace with a single one. How to do this in Java. Some examples:

123345应该是12345
77433211应该是74321

123345 should be 12345 77433211 should be 74321

推荐答案

可能是 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"));

这篇关于如何在Java中找到两个相邻的重复数字并用一个数字替换它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆