【问题标题】:Java regex to replace numeric values with quotes numeric valuesJava正则表达式用引号数值替换数值
【发布时间】:2021-09-12 05:56:32
【问题描述】:

有人可以帮忙用正则表达式用单引号替换给定字符串中的所有整数和双精度: Key1=a,Key2=2,Key3=999.6,Key4=8888,Key5=true

有了这个: Key1=a,Key2='2',Key3='999.6',Key4='8888',Key5=true

我想使用正则表达式组捕获规则来替换=之后开始的所有数字字符串并替换为''。

【问题讨论】:

    标签: java regex


    【解决方案1】:

    环顾四周:

    String quoted = str.replaceAll("(?<==)\\d+(\\.\\d+)?(?=,|$)", "'$0'");
    

    整个匹配,即第 0 组,是用第 0 组周围的引号替换的数字。

    匹配以向后查找等号开始,以向前查找逗号或输入结尾结束。

    【讨论】:

      【解决方案2】:

      您可以在这里尝试使用正则表达式替换所有方法:

      String input = "Key1=a,Key2=2,Key3=999.6,Key4=8888,Key5=true";
      String output = input.replaceAll("([^,]+)=(\\d+(?:\\.\\d+)?)", "$1='$2'");
      System.out.println(output);  // Key1=a,Key2='2',Key3='999.6',Key4='8888',Key5=true
      

      这里是使用的正则表达式模式的解释:

      ([^,]+)             match and capture the key in $1
      =                   match =
      (\\d+(?:\\.\\d+)?)  match and capture an integer or float number in $2
      

      然后,我们替换为$1='$2',引用数字值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-12
        • 2014-01-12
        • 2016-05-23
        • 2020-07-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多