Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing multiple occurrences of characters

Tags:

java

regex

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

like image 644
user2408677 Avatar asked May 22 '13 08:05

user2408677


1 Answers

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.

like image 144
Tim Radcliffe Avatar answered Nov 07 '22 17:11

Tim Radcliffe