2017-05-30 34 views
0

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

例如,转换这样的:

0this 1is02 an example33 string44 

这样:

*0*this *1*is*02* an example*33* string*44* 
+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

+0

太好了,谢谢。 – buswedg