Java 正则表达式替换和插入
我正在编写一个java来插入“*”,在这里可以进行乘法,所以5sqrt(25)将是5*sqrt(25),依此类推。为此,我使用regexp匹配字母“(\d)([a-z])旁边的一个数字。我遇到的问题是,第一次匹配后的字母和数字将替换为第一次匹配的字母和数字。因此,如果我的输入是“5sqrt(25)+89函数(4)”,我将得到 “5*sqrt(25)+85*sfunction(4)”,我正在使用的代码示例是Java 正则表达式替换和插入,java,regex,replace,insert,Java,Regex,Replace,Insert,我正在编写一个java来插入“*”,在这里可以进行乘法,所以5sqrt(25)将是5*sqrt(25),依此类推。为此,我使用regexp匹配字母“(\d)([a-z])旁边的一个数字。我遇到的问题是,第一次匹配后的字母和数字将替换为第一次匹配的字母和数字。因此,如果我的输入是“5sqrt(25)+89函数(4)”,我将得到 “5*sqrt(25)+85*sfunction(4)”,我正在使用的代码示例是 public static void demo(){ String regex =
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+t5+t5+t,而不是我想要的5+t8+x9+y
我应该怎么做呢?使用
string.replaceAll
函数
System.out.println("5t 8x 9y".replaceAll("(\\d)([a-z])", "$1+$2"));
输出:
5+t 8+x 9+y
(?在这种情况下,替换所有适合的部件。您可以尝试:
<target_string>.replaceAll("(\\d)([a-z])", "$1*$2")
.replaceAll(“(\\d)([a-z])”,“$1*$2”)
是的,你说得对。$1
指的是第1组,$2
指的是第2组。环顾四周会做什么?为什么要添加它们?@tarFish trystring.replaceAll(?
<target_string>.replaceAll("(\\d)([a-z])", "$1*$2")