gpt4 book ai didi

Java : replace regexp with processed match

转载 作者:搜寻专家 更新时间:2023-10-31 19:42:16 27 4
gpt4 key购买 nike

假设我有以下字符串:

String in = "A xx1 B xx2 C xx3 D";

我想要结果:

String out = "A 1 B 4 C 9 D";

我想以最类似的方式来做:

String out = in.replaceAll(in, "xx\\d",
new StringProcessor(){
public String process(String match){
int num = Integer.parseInt(match.replaceAll("x",""));
return ""+(num*num);
}
}
);

也就是说,使用字符串处理器在进行实际替换之前修改匹配的子字符串。

是否已经编写了一些库来实现这一点?

最佳答案

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

关于Java : replace regexp with processed match,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2207769/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com