Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Probably a <code>replaceAll("(\\d)\\1+", "$1")</code></p> <ul> <li><code>$</code> plays a special role in a replacing string, designating the first capturing group.</li> <li><code>+</code> allows for replacing as many identical number as possible <code>(\\d)\\1</code> would only replace them by pair: <code>777xx</code> => <code>77xx</code> (thank you <a href="https://stackoverflow.com/users/12267/ben-doom">Ben Doom</a> for the remark)</li> </ul> <p>So:</p> <pre><code>System.out.println("77433211".replaceAll("(\\d)\\1+", "$1")); </code></pre> <p>will return</p> <pre><code>74321 </code></pre> <hr> <pre><code>String java.lang.String.replaceAll(String regex, String replacement) </code></pre> <p>Replaces each substring of this string that matches the given regular expression with the given replacement. </p> <p>An invocation of this method of the form <code>str.replaceAll(regex, repl)</code> yields exactly the same result as the expression </p> <pre><code>java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl) </code></pre> <hr> <p><strong>Warning</strong>: <code>String.replaceAll()</code> function does not modify the String on which it is applied. It returns a modified String (or <em>a new String with the same content</em> if the pattern does not match anything)</p> <p>So you need to affect the result of a <code>replaceAll()</code> call to itself to actually update your String with the regexp changes.</p> <pre><code>String aString = "77433211" aString = aString.replaceAll("(\\d)\\1+", "$1")); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload