我正在尝试用唯一的替换来替换特定字符串的所有实例。
我想要什么:
如果我有这个字符串:
String testScript = "while(true) { } while (10 < 7) { } while((10 < 7)) { }";
我想要这样的输出:
while(arg0 < 5000 && true) { } while(arg1 < 5000 && 10 < 7) { } while(arg2 < 5000 && (10 < 7)) { }
我有什么:
但是,传递给 replaceAll
的字符串不会再次被查询(现在我想起来很明显)。
while(arg0 < 5000 && true) { } while(arg0 < 5000 && 10 < 7) { } while(arg0 < 5000 && (10 < 7)){ }
一如既往,我们非常感谢任何回答或评论。
SSCCE:
public static void main(String[] args) {
int counter = 0;
String testScript = "while(true) { } while (10 < 7) { } while((10 < 7)) { }";
String out = testScript.replaceAll("while\\s*\\(", "while(arg" + (counter++) + " < 5000 && ");
System.out.println(out);
}
最佳答案
看来您正在寻找 Matcher
类中的 appendReplacement
和 appendTail
方法。
这两种方法都需要临时缓冲区,其中将放置新(替换)版本的字符串。在这种情况下,使用 StringBuffer
。
它们的目的是将修改后的文本 block 添加到缓冲区中
appendReplacement(StringBuffer sb, String replacement)
从最后一个匹配项(或者如果是从字符串开头的第一个匹配项)到当前匹配项开始 + 替换找到匹配项的文本appendTail(StringBuffer sb)
当没有剩余匹配时,但我们还需要在最后一个匹配后添加文本(或者如果没有匹配整个原始字符串)。
换句话说,如果你有文本 xxxxfooxxxxxfooxxxx
并且你想将 foo
替换为 bar
匹配器将需要调用
xxxxfooxxxxxfooxxxx
1. appendReplacement ^^^^^^^ will add to buffer xxxxbar
1. appendReplacement ^^^^^^^^ will add to buffer xxxxxbar
3. appendTail ^^^^ will add to buffer xxxx
所以在这个缓冲区之后将包含xxxxbarxxxxxbarxxxx
。
演示
String testScript = "while(true) { } while (10 < 7) { } while((10 < 7)) { }";
Pattern p = Pattern.compile("while\\s*\\(");
Matcher m = p.matcher(testScript);
int counter = 0;
StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb, "while(arg"+ (counter++) + " < 5000 && ");
}
m.appendTail(sb);
String result = sb.toString();
System.out.println(result);
输出:
while(arg0 < 5000 && true) { } while(arg1 < 5000 && 10 < 7) { } while(arg2 < 5000 && (10 < 7)) { }
关于java - 用唯一替换替换字符串中的所有实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25081668/