views:

183

answers:

2

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 ?

+3  A: 

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());
finnw
Great, really overlooked this method ! Thanks a ton.
subtenante
I didn't know about `appendReplacement` and `appendTail`. Thanks a lot.
NawaMan
+1  A: 

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.

NawaMan
Indeed, that's nice. Thanks! :)
subtenante