简体   繁体   中英

Insert asterisks around numbers in string using Java

What would be the best way to add asterisks before and after any numbers which appear within a string using Java? Note that multiple digits which appear joined would be interpreted as a single number.

for example, convert this:

0this 1is02 an example33 string44

to this:

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

One approach is to a String#replaceAll() on your input string, matching on \\d+ and replacing on *$1* . In other words, replace every cluster of digits with that cluster of digits surrounded by asterisks.

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

Output:

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

Demo here:

Rextester

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM