代码之家  ›  专栏  ›  技术社区  ›  glmxndr Amir Raminfar

用处理过的匹配替换ReXEP

  •  5
  • glmxndr Amir Raminfar  · 技术社区  · 14 年前

    假设我有以下字符串:

    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 回复  |  直到 14 年前
        1
  •  7
  •   finnw    14 年前

    使用 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());
    
        2
  •  1
  •   NawaMan    14 年前

    你可以很容易地写自己。以下是如何:

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

    希望这有帮助。