简体   繁体   English

如何匹配这种模式? (Java /正则表达式)

[英]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某种方式与%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? 任何想法?

try resetting the tokenMatcher in the loop. 尝试在循环中重置tokenMatcher

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

System.out.println(value);

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. 原因是replaceFirst()将匹配器重置为开头,但不更改当前匹配的字符串,它仍然包含旧字符串。 You have to do that yourself to update the matcher. 您必须自己进行操作以更新匹配器。

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

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

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();

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

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