M. Nowin M. Nowin - 1 year ago 69
Java Question

Java Regex compress String

I have random String for example

I need make regex wich schare the text for groups to get effect
. My regex looks like that
but he lost single letters, so in this sample

Maybe someone would have an idea?

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Compress {
public static void main(String[] args) {
String text = "aaaaaaBccccCCCCd";
String regex = "(\\D+)\\D*\\1"; // or (.+).*\\1
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
String result = new String();
while (matcher.find()) {
String letter = matcher.group().substring(0, 1);
String numberOfLetter = String.valueOf(matcher.group().length());
result = result + letter + numberOfLetter;

Thank you.

Answer Source

Use the following approach based on Matcher#appendReplacement:

String text = "aaaaaaBccccCCCCd"; //a6B1c4C4d1
String regex = "(.)(\\1*)"; 
String pattern = "test";
Pattern r = Pattern.compile(regex);
Matcher m = r.matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
    m.appendReplacement(sb, m.group(1) + (m.group(2).length()+1));

See the Java demo

The (.)(\1*) will capture any char into Group 1 and then will capture into Group 2 zero or more repetitions of the same content. In the "callback", Group 1 is concatenated with the length of Group 2 incremented to account for the Group 1 length.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download