2010-02-05 45 views
5

比方說,我有以下字符串:的Java:與加工匹配替換正則表達式

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

也就是說,使用字符串處理器在進行實際替換之前修改匹配的子字符串。

是否有一些圖書館已經寫入實現這一目標?

回答

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()); 
+0

太好了,真的被忽視了這種方法!萬分感謝。 – glmxndr 2010-02-05 14:33:44

+0

我不知道'appendReplacement'和'appendTail'。非常感謝。 – NawaMan 2010-02-05 14:56:44

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

希望這會有所幫助。

+0

確實,這很好。謝謝! :) – glmxndr 2010-02-05 15:23:43