5

Let's say I have the following string :

String in = "A xx1 B xx2 C xx3 D";

I want the result :

String out = "A 1 B 4 C 9 D";

I would like to do it a way resembling the most :

String out = in.replaceAll(in, "xx\\d",
    new StringProcessor(){
        public String process(String match){ 
            int num = Integer.parseInt(match.replaceAll("x",""));
            return ""+(num*num);
        }
    } 
);

That is, using a string processor which modifies the matched substring before doing the actual replace.

Is there some library already written to achieve this ?

2 Answers 2

7

Use Matcher.appendReplacement():

    String in = "A xx1 B xx2 C xx3 D";
    Matcher matcher = Pattern.compile("xx(\\d)").matcher(in);
    StringBuffer out = new StringBuffer();
    while (matcher.find()) {
        int num = Integer.parseInt(matcher.group(1));
        matcher.appendReplacement(out, Integer.toString(num*num));
    }
    System.out.println(matcher.appendTail(out).toString());
Sign up to request clarification or add additional context in comments.

2 Comments

Great, really overlooked this method ! Thanks a ton.
I didn't know about appendReplacement and appendTail. Thanks a lot.
1

You can write yourself quite easily. Here is how:

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


public class TestRegEx {

    static public interface MatchProcessor {
        public String processMatch(final String $Match);
    }
    static public String Replace(final String $Str, final String $RegEx, final MatchProcessor $Processor) {
        final Pattern      aPattern = Pattern.compile($RegEx);
        final Matcher      aMatcher = aPattern.matcher($Str);
        final StringBuffer aResult  = new StringBuffer();

        while(aMatcher.find()) {
            final String aMatch       = aMatcher.group(0);
            final String aReplacement = $Processor.processMatch(aMatch);
            aMatcher.appendReplacement(aResult, aReplacement);
        }

        final String aReplaced = aMatcher.appendTail(aResult).toString();
        return aReplaced;
    }

    static public void main(final String ... $Args) {
        final String aOriginal = "A xx1 B xx2 C xx3 D";
        final String aRegEx    = "xx\\d";
        final String aReplaced = Replace(aOriginal, aRegEx, new MatchProcessor() {
            public String processMatch(final String $Match) {
                int num = Integer.parseInt($Match.substring(2));
                return ""+(num*num);
            }
        });

        System.out.println(aReplaced);
    }
}

Hope this helps.

1 Comment

Indeed, that's nice. Thanks! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.