是否可以讓String.replaceAll
將當前更換件的數量(計數)放入更換件中?是否可以在String.replaceAll中使用當前替換的數量?
這樣"qqq".replaceAll("(q)", "something:$1 ")
會導致"1:q 2:q 3:q"
?
有什麼我可以替代東西在上面的代碼中,使其解析爲當前的替換計數?
是否可以讓String.replaceAll
將當前更換件的數量(計數)放入更換件中?是否可以在String.replaceAll中使用當前替換的數量?
這樣"qqq".replaceAll("(q)", "something:$1 ")
會導致"1:q 2:q 3:q"
?
有什麼我可以替代東西在上面的代碼中,使其解析爲當前的替換計數?
這裏是這樣做的一種方法:
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);
不,與replaceAll
方法不同。唯一的反向引用是\n
其中n是匹配的第n個捕獲組。
對於這一點,你必須創建自己的的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
謝謝,雖然我的問題的答案是*否*您的方法是最接近的匹配 – 2011-12-15 11:26:39