regular expression to replace two (or more) consecutive characters by only one?

Tags: regex java
Question!

In java, which regular expression can be used to replace these, for example:

before: aaabbb after: ab

before: 14442345 after: 142345

thanks!

By : Alex. S.


Answers

Sugared with a Java 7 : Named Groups

static String cleanDuplicates(@NonNull final String val) { 
      assert val != null;
      return val.replaceAll("(?<dup>.)\\k<dup>+","${dup}");
}


String a = "aaabbb";
String b = a.replaceAll("(.)\\1+", "$1");
System.out.println("'" + a + "' -> '" + b + "'");
By : smink


In Perl:

tr/a-z0-9//s;

Example:

$ perl -E'@a = (aaabbb, 14442345); for(@a) { tr/a-z0-9//s; say }'
ab
142345

If Java has no tr analog then:

s/(.)\1+/$1/sg; 
#NOTE: `s` modifier. It takes into account consecutive newlines.

Example:

$ perl -E'@a = (aaabbb, 14442345); for(@a) { s/(.)\1+/$1/sg; say }'
ab
142345


This video can help you solving your question :)
By: admin