glm*_*ndr 5 java regex replace
假设我有以下字符串:
String in = "A xx1 B xx2 C xx3 D";
Run Code Online (Sandbox Code Playgroud)
我想要结果:
String out = "A 1 B 4 C 9 D";
Run Code Online (Sandbox Code Playgroud)
我想以类似的方式做到这一点:
String out = in.replaceAll(in, "xx\\d",
new StringProcessor(){
public String process(String match){
int num = Integer.parseInt(match.replaceAll("x",""));
return ""+(num*num);
}
}
);
Run Code Online (Sandbox Code Playgroud)
也就是说,使用字符串处理器在执行实际替换之前修改匹配的子字符串.
是否已经编写了一些库来实现这一目标?
用途Matcher.appendReplacement():
String in = "A xx1 B xx2 C xx3 D";
Matcher matcher = Pattern.compile("xx(\\d)").matcher(in);
StringBuffer out = new StringBuffer();
while (matcher.find()) {
int num = Integer.parseInt(matcher.group(1));
matcher.appendReplacement(out, Integer.toString(num*num));
}
System.out.println(matcher.appendTail(out).toString());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1796 次 |
| 最近记录: |