是否可以在String.replaceAll中使用当前替换的数量?

时间:2011-12-15 10:39:30

标签: java regex string

是否可以让String.replaceAll将当前替换的号码(计数)放入替换中?

因此"qqq".replaceAll("(q)", "something:$1 ")会导致"1:q 2:q 3:q"

我可以在上面的代码中替换某些,以使其解析为当前的替换计数吗?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

不,不是replaceAll方法。唯一的反向引用是\n,其中n是匹配的第n个捕获组。

答案 2 :(得分: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;
}   
}

我得到的输出是:

  

替换为:

     

ali:0 ali:1 ali:2 ali:3 ali:4 ali:5