在使用Java出现在字符串中的任何数字之前和之后添加星号的最佳方法是什么?请注意,出现连接的多个数字将被解释为单个数字.
例如,将此转换为:
0this 1is02 an example33 string44
Run Code Online (Sandbox Code Playgroud)
对此:
*0*this *1*is*02* an example*33* string*44*
Run Code Online (Sandbox Code Playgroud)
一种方法是String#replaceAll()在输入字符串上进行匹配,匹配\d+和替换*$1*.换句话说,用星号包围的数字簇替换每个数字簇.
String input = "0this 1is02 an example33 string44";
input = input.replaceAll("(\\d+)", "*$1*");
System.out.println(input);
Run Code Online (Sandbox Code Playgroud)
输出:
*0*this *1*is*02* an example*33* string*44*
Run Code Online (Sandbox Code Playgroud)
在这里演示: