正则表达式替换和插入

时间:2014-12-03 05:44:42

标签: java regex replace insert

我正在编写一个java来插入'*',其中乘法将被完成,因此5sqrt(25)将是5 * sqrt(25),依此类推。要做到这一点,我使用正则表达式来匹配字母“(\ d)([az])旁边的数字我遇到的问题是第一次匹配后的字母和数字被替换为匹配的字母和数字第一个,所以如果我的输入是“5sqrt(25)+ 89function(4)”我会得到输出 “5 * sqrt(25)+8 5 * s unction(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这就是我想要的。

我应该怎么做?

3 个答案:

答案 0 :(得分:0)

使用string.replaceAll功能。

System.out.println("5t 8x 9y".replaceAll("(\\d)([a-z])", "$1+$2"));

输出:

5+t 8+x 9+y

答案 1 :(得分:0)

(?<=\\d)(?=[a-z])

不要使用matches,而只需replace。替换为*

参见演示。

http://regex101.com/r/yR3mM3/23

答案 2 :(得分:0)

在这种情况下,

替换所有适合。你可以尝试:

<target_string>.replaceAll("(\\d)([a-z])", "$1*$2")