Java:用已处理的匹配替换正则表达式

时间:2010-02-05 14:19:35

标签: java regex replace

假设我有以下字符串:

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

我想要结果:

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

我想以类似的方式做到这一点:

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

也就是说,使用字符串处理器在执行实际替换之前修改匹配的子字符串。

是否已经编写了一些库来实现这一目标?

2 个答案:

答案 0 :(得分:7)

使用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());

答案 1 :(得分:1)

你可以很容易地写自己。方法如下:

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);
    }
}

希望这有帮助。