views:

1322

answers:

4

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 should be 12345 77433211 should be 74321

A: 

using a regex:

var myString='123345'
myString.replace(/([0-9])\1/g,'$1')

that will match exactly 2 repeats.

'123334'.replace(/([0-9])\1+/g,'$1')
Cipher
That's not Java... but the idea is sound.
Jon Skeet
lol i see that now...
Cipher
You could use this regexp in combination with java.util.regex.Pattern en java.util.regex.Matcher classes.
Ruben
There's a replaceAll() convenience method in the String class, so you don't have to use Pattern or Matcher, but you have to write the regex in the form of a String literal, as VonC demonstrated, because Java doesn't have regex literals.
Alan Moore
+11  A: 

Probably a replaceAll("(\\d)\\1+", "$1")

  • '$' 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)

So:

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

will return

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.

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)


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)

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"));
VonC
It should be noted that this *only* works in pairs, so 777 becomes 77 ((77)7) and 7777 becomes 77 ((77)(77)). To replace all repeats, use /(\\d)\\1+/
Ben Doom
A: 

This is a regular expression mathing two repeating digits (x being the digit)

[x]{2}(?!=[x])
Drejc
+4  A: 

I finally did it myself. Those who are looking for the solution, this is how I did it:

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);
    }
}

Even simpler:

**word = word.replaceAll("(\\d)\\1", "$1");**
askgelal
Yes, but again, a simple "77433211".replaceAll("(\\d)\\1", "$1"); is enough ;)
VonC
Yes that did too, I just forgot to assign the return value and thought that it doesn't work. Thanks VonC for your help. A couple of votes to you for that :-)
askgelal