有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java正则表达式将数值替换为引号数值

有人能帮我用正则表达式替换给定字符串中的所有整数和双精度,并用单引号括起来吗 键1=a,键2=2,键3=999.6,键4=8888,键5=true

为此: Key1=a,Key2='2',Key3='999.6',Key4='8888',Key5=true

我想使用正则表达式组捕获规则替换=之后的所有数字字符串startng,并替换为“”


共 (2) 个答案

  1. # 1 楼答案

    在每一端使用环视:

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

    整个匹配项(即组0)是要用组0周围的引号替换的数字

    匹配从查找后面的equals开始,以查找前面的逗号或输入结尾结束

  2. # 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'替换,引用数值