簡體   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