Sumanth
Sumanth

Reputation: 383

Replacing a Complex Sequence of Characters in Java

My requirement is that I read from a file and replace the sequence of two semicolon occurences (;;) in the file with 0 .

Problem here is that, when there are more than two sequential occurences like eg ';;;;;;'.

I am not able to replace 0 correctly ,any suggestions on achieving it in Java.

Sample input would be 5;4;;;4;4;;;;4;;;3;;1;5;4;5;;3;5;;5;;5;3;;;;;;;;;;;;5;

Output would be 5 4 0 0 4 4 0 0 0 4 0 0 3 0 1 5 4 5 0 3 5 0 5 0 5 3 0 0 0 0 0 0 0 0 0 0 0 5

Upvotes: 0

Views: 95

Answers (1)

Gerardo
Gerardo

Reputation: 979

I think this is what you want

import java.util.regex.Pattern;
import java.util.regex.Matcher;

class Untitled {
    public static void main(String[] args) {
        String replaced = replaceSemiColons("5;4;;;4;4;;;;4;;;3;;1;5;4;5;;3;5;;5;;5;3;;;;;;;;;;;;5;");
        replaced = replaced.replace(";", "");
        System.out.println(replaced);
    }

    public static String replaceSemiColons(String string) {
        StringBuffer replaced = new StringBuffer(string);
        Pattern pattern = Pattern.compile(";;+");
        Matcher matcher = pattern.matcher(replaced.toString());
        while(matcher.find()){
            replaced.replace(matcher.start(), matcher.end(), new String(new char[matcher.end() - matcher.start() - 1]).replace("\0", "0"));
            matcher = pattern.matcher(replaced.toString());
        }
        return replaced.toString();
    }
}

If someone has a better answer you should take it.

Upvotes: 1

Related Questions