【发布时间】:2014-12-03 05:44:41
【问题描述】:
我正在编写一个 java 来插入 '*' 进行乘法运算,因此 5sqrt(25) 将是 5*sqrt(25) 等等。为此,我使用正则表达式匹配字母“(\d)([a-z]) 旁边的数字,我遇到的问题是第一次匹配后的字母和数字被替换为匹配的字母和数字第一个,所以如果我的输入是“5sqrt(25)+89function(4)”我会得到输出 "5*sqrt(25)+85*sunction(4)" 和我使用的代码示例是
public static void demo(){
String regex = "(\\d)([a-z])";
String demo = "5t 8x 9y";
Pattern pat = Pattern.compile(regex);
Matcher mat = pat.matcher(demo);
if(mat.find()){
System.out.println(mat.replaceAll(mat.group(1) + "+" + mat.group(2)));
}
}
这输出 5+t 5+t 5+t,而不是我想要的 5+t 8+x 9+y。
我该怎么办?
【问题讨论】: