Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java : regex to add space before number

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", " "))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

but it doesn’t seem to do the job.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading