Oleg Mikheev
Oleg Mikheev

Reputation: 17444

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?

So that "qqq".replaceAll("(q)", "something:$1 ") would result in "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?

Upvotes: 3

Views: 105

Answers (3)

alishaik786
alishaik786

Reputation: 3726

For this you have to create your own replaceAll() method.

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

Upvotes: 0

codaddict
codaddict

Reputation: 455122

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

Upvotes: 3

bezmax
bezmax

Reputation: 26132

No, not with the replaceAll method. The only backreference is \n where n is the n'th capturing group matched.

Upvotes: 1

Related Questions