Home > Blockchain >  Java : regex to add space before number
Java : regex to add space before number

Time:04-09

I would like to add a space before each number.

Here : AS400 would become AS 4 0 0

I have tried : line.replaceAll("[0-9]/g", " "))

but it doesn't seem to do the job.

CodePudding user response:

You can use

String result = line.replaceAll("\\d", " $0");

Or, if you do not want to add a space at the start:

String result = line.replaceAll("(?!^)\\d", " $0");

The \d pattern matches any digit, and replaceAll will match and replace all occurrences, /g at the end of the pattern only does harm and needs removing. (?!^) means "not at the start of the string".

The $0 placeholder/replacement backreference in the replacement refers to the whole match value.

See the regex demo.

  • Related