znat
znat

Reputation: 13474

How to match this pattern ? (Java/regex)

I need to transform the string:

"%s blabla %s"

into:

"%1$s blabla %2$s"

My code is as follows:

Pattern pattern = Pattern.compile("%s");
Matcher tokenMatcher = pattern.matcher(value);
int index = 1;
while(tokenMatcher.find()){
    String replacement = "%"+String.valueOf(index++)+"\\$s";        
    value = tokenMatcher.replaceFirst(replacement);
    System.out.println(value);
}

The problem is that the program gets in an infinite loop and I don't understand why. Somehow %1$s is matched by %s

%1$s blabla %s
%2$s blabla %s
%3$s blabla %s
%4$s blabla %s
%5$s blabla %s
%6$s blabla %s
%7$s blabla %s
%8$s blabla %s
%9$s blabla %s
%10$s blabla %s
etc...

Any idea?

Upvotes: 1

Views: 172

Answers (4)

orangegoat
orangegoat

Reputation: 2703

while(matcher.find()){
    matcher.appendReplacement(stringBuffer, "%" + String.valueOf(index++) + "\\$s");
}
matcher.appendTail(stringBuffer);

http://tutorials.jenkov.com/java-regex/matcher.html#8

Upvotes: 1

Rais Alam
Rais Alam

Reputation: 7016

Try below code

 StringBuilder stringBuilder = new StringBuilder();
        int i = 1;

        for (String s : input.split("%s")) {
            stringBuilder.append(String.format("%s %d", s, "%"+i+++"$"));


       }

String newString = stringBuilder.toString();

Upvotes: 0

Cyrille Ka
Cyrille Ka

Reputation: 15533

You have to reset your matcher with the new value:

while (tokenMatcher.find()) {
  String replacement = "%" + String.valueOf(index++) + "\\$s";
  value = tokenMatcher.replaceFirst(replacement);
  tokenMatcher.reset(value); // reset
  System.out.println(value);
}

The reason is that replaceFirst() reset the matcher to the beginning but does not change the string it is currently matching, it's still contains the old string. You have to do that yourself to update the matcher.

Upvotes: 2

Tarandeep Gill
Tarandeep Gill

Reputation: 1534

try resetting the tokenMatcher in the loop.

while(tokenMatcher.find()){
    String replacement = "%"+String.valueOf(index++)+"\\$s";        
    value = tokenMatcher.replaceFirst(replacement);
    tokenMatcher = pattern.matcher(value);
}

System.out.println(value);

Upvotes: 2

Related Questions