1

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.

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.