繁体   English   中英

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

[英]Is it possible to use the number of current replacement in 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;
}   
}

我得到的输出是:

替换为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM