使用Java在字符串中的数字周围插入星号

时间:2017-05-30 04:51:29

标签: java

在使用Java出现在字符串中的任何数字之前和之后添加星号的最佳方法是什么?请注意,出现连接的多个数字将被解释为单个数字。

例如,将其转换为:

0this 1is02 an example33 string44

到此:

*0*this *1*is*02* an example*33* string*44*

1 个答案:

答案 0 :(得分:6)

一种方法是在输入字符串上加String#replaceAll(),在\d+上匹配并替换*$1*。换句话说,用星号包围的数字簇替换每个数字簇。

String input = "0this 1is02 an example33 string44";
input = input.replaceAll("(\\d+)", "*$1*");
System.out.println(input);

<强>输出:

*0*this *1*is*02* an example*33* string*44*

在这里演示:

Rextester