简体   繁体   English

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

[英]Is it possible to use the number of current replacement in String.replaceAll?

Is it possible to make String.replaceAll put the number (count) of the current replacement into the replacement being made? 是否有可能使String.replaceAll将当前替换的数量(计数)放入替换中?

So that "qqq".replaceAll("(q)", "something:$1 ") would result in "1:q 2:q 3:q" ? 那么"qqq".replaceAll("(q)", "something:$1 ")会导致"1:q 2:q 3:q"

Is there anything that I can replace something in the code above with, to make it resolve into the current substitution count? 有什么东西可以替换上面的代码中的东西 ,以使其解析为当前的替换计数?

Here is one way of doing this: 这是一种方法:

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 看见

No, not with the replaceAll method. 不,不是使用replaceAll方法。 The only backreference is \\n where n is the n'th capturing group matched. 唯一的反向引用是\\n ,其中n是匹配的第n个捕获组。

For this you have to create your own replaceAll() method. 为此,您必须创建自己的replaceAll()方法。

This helps you: 这有助于您:

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

The output I got is: 我得到的输出是:

Replaced As: 替换为:

ali:0 ali:1 ali:2 ali:3 ali:4 ali:5 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