2011-12-15 17 views

回答

3

這裏是這樣做的一種方法:

StringBuffer resultString = new StringBuffer(); 
String subjectString = new String("qqqq"); 
Pattern regex = Pattern.compile("q"); 
Matcher regexMatcher = regex.matcher(subjectString); 
int i = 1; 
while (regexMatcher.find()) { 
    regexMatcher.appendReplacement(resultString, i+":"+regexMatcher.group(1)+" "); 
    i++; 
} 
regexMatcher.appendTail(resultString); 
System.out.println(resultString); 

See it

+0

謝謝,雖然我的問題的答案是*否*您的方法是最接近的匹配 – 2011-12-15 11:26:39

1

不,與replaceAll方法不同。唯一的反向引用是\n其中n是匹配的第n個捕獲組。

0

對於這一點,你必須創建自己的的replaceAll()方法。

這可以幫助你:

public class StartTheClass 
{  
public static void main(String[] args) 
{  
    String string="wwwwww"; 
    System.out.println("Replaced As: \n"+replaceCharector(string, "ali:", 'w'));  
} 

public static String replaceCharector(String original, String replacedWith, char toReplaceChar) 
{ 
    int count=0; 
    String str = ""; 
    for(int i =0; i < original.length(); i++) 
    { 

     if(original.charAt(i) == toReplaceChar) 
     { 
      str += replacedWith+(count++)+" ";//here add the 'count' value and some space; 
     } 
     else 
     { 
      str += original.charAt(i); 
     } 

    } 
    return str; 
} 
} 

我得到的輸出是:

替換爲:

阿里:0阿里:1阿里:2阿里:3阿里:4阿里:5

相關問題