I found
String seq = "123456789";
String regex = seq.replaceAll(".", "(?=[$0-9]([a-z]))?") + "[0-9][a-z]";
String repl = seq.replaceAll(".", "\\$$0");
Which turns 4a into aaaa, 3b into bbb and so on... I need the opposite and I couldn't figure it out. I need to turn aaaa into 4a, bbb into 3b and so on. Thanks a lot
Here is an example of a run-length encoding/decoding implementation in Java:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RunLengthEncoding {
public static String encode(String source) {
StringBuffer dest = new StringBuffer();
for (int i = 0; i < source.length(); i++) {
int runLength = 1;
while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
runLength++;
i++;
}
dest.append(runLength);
dest.append(source.charAt(i));
}
return dest.toString();
}
public static String decode(String source) {
StringBuffer dest = new StringBuffer();
Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
int number = Integer.parseInt(matcher.group());
matcher.find();
while (number-- != 0) {
dest.append(matcher.group());
}
}
return dest.toString();
}
public static void main(String[] args) {
String example = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
System.out.println(encode(example));
System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B"));
}
}
Taken from here:
http://rosettacode.org/wiki/Run-length_encoding
(this page includes equivalent examples in 72 different programming languages to achieve the same goal)
To achieve what you are asking for, you would use the "encode" method.
Tested here: http://www.browxy.com/SubmittedCode/21369
Regex on its own is not a suitable tool for trying to achieve this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With