如何用特定字符替换重复的String模式集?

时间:2014-09-03 13:26:58

标签: java regex

我有一个像这样的字符串

示例输入

00000000255255255255000000000255255000000000000002552552552552552552550000000000

我需要使用regx

替换此字符串,如下所示

示例输出

00000000000,0000000000000000,000000000000000,0000000000

假设代码是这样的

s="00000000255255255255000000000255255000000000000002552552552552552552550000000000";
s.replace("regularexpression",",");

2 个答案:

答案 0 :(得分:4)

我猜你的样本输出错了......

如果您想用逗号替换字符串中所有连续的非零数字组,请尝试以下操作:

s = s.replaceAll("[1-9]+", ",");

如果您正在尝试替换所有重复的字符串" 255"用逗号一次或多次,试试这个:

s = s.replaceAll("(255)+", ",");

答案 1 :(得分:1)

如果您希望拆分非0位数,这是一个解决方案:

String input = "00000000255255255255000000000255255000000000000002552552552552552552550000000000";
//                 | String representation of the split array
//                 |                     | splitting...
//                 |                     |      |... on a character class...
//                 |                     |      || ...for any digit non-0
//                 |                     |      ||   | in 1+ sequential instances
System.out.println(Arrays.toString(input.split("[1-9]+")));

<强>输出

[00000000, 000000000, 00000000000000, 0000000000]