我试图用唯一的替换来替换特定字符串的所有实例。
我想要什么:
如果我有这个字符串:
String testScript = "while(true) { } while (10 < 7) { } while((10 < 7)) { }";
Run Code Online (Sandbox Code Playgroud)
我想要这个输出:
while(arg0 < 5000 && true) { } while(arg1 < 5000 && 10 < 7) { } while(arg2 < 5000 && (10 < 7)) { }
Run Code Online (Sandbox Code Playgroud)
我拥有的:
但是,传入的字符串replaceAll不会再次被查询(现在我想起来很明显)。
while(arg0 < 5000 && true) { } while(arg0 < 5000 && 10 < 7) { } while(arg0 < 5000 && (10 < 7)){ }
Run Code Online (Sandbox Code Playgroud)
一如既往,我们非常感谢任何答案或评论。
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);
}
Run Code Online (Sandbox Code Playgroud)
看来您正在寻找类中的appendReplacement方法。appendTailMatcher
这两种方法都需要临时缓冲区,其中将放置新的(替换的)版本的字符串。在这种情况下StringBuffer使用。
它们的目的是添加修改文本的缓冲区块
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
Run Code Online (Sandbox Code Playgroud)
所以此缓冲区之后将包含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);
Run Code Online (Sandbox Code Playgroud)
输出:
while(arg0 < 5000 && true) { } while(arg1 < 5000 && 10 < 7) { } while(arg2 < 5000 && (10 < 7)) { }
Run Code Online (Sandbox Code Playgroud)