Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : replace regexp with processed match

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 ?

like image 314
glmxndr Avatar asked Feb 05 '10 14:02

glmxndr


2 Answers

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());
like image 182
finnw Avatar answered Oct 04 '22 03:10

finnw


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.

like image 26
NawaMan Avatar answered Oct 04 '22 03:10

NawaMan