buswedg
buswedg

Reputation: 47

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*

Upvotes: 0

Views: 172

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521339

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

Upvotes: 6

Related Questions