首页 > 解决方案 > Java正则表达式用引号数值替换数值

问题描述

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

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

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

标签: javaregex

解决方案


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

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',引用数字值。


推荐阅读