【问题标题】:Regex replace and insert正则表达式替换和插入
【发布时间】: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。

我该怎么办?

【问题讨论】:

    标签: java regex replace insert


    【解决方案1】:

    使用string.replaceAll 函数。

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

    输出:

    5+t 8+x 9+y
    

    【讨论】:

    • 是的,你是对的。 $1 指第 1 组,$2 指第 2 组。
    【解决方案2】:
    (?<=\\d)(?=[a-z])
    

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

    查看演示。

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

    【讨论】:

    • 环顾四周有什么作用?为什么要添加它们?
    • @tarFish 试试string.replaceAll("(?&lt;=\\d)(?=[a-z])", "*")。所以你不需要任何捕获
    【解决方案3】:

    Replace All 非常适合这种情况。你可以试试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多