This is my string:

" "hello": 0, "zulu": 1,234, "Bravo": 987.456 "

I wish to replace any number (integer or real with a thousand's separator or not) in the string using regex and get this new string:

 "hello": "0", "zulu": "1,234", "Bravo": "987.456" "

How do I solve this problem?

1 Answers

Pushpesh Kumar Rajwanshi On Best Solutions

You can capture the numbers using this regex,


Here, \d+ captures a number having one or more digits and (?:[,.]\d+)* optionally captures more digits that are either comma or dot separated, and replace them with "$0" where $0 represents whole match.

Regex Demo

Java code demo,

String s = "\" \"hello\": 0, \"zulu\": 1,234, \"Bravo\": 987.456 \"";
System.out.println(s.replaceAll("\\d+(?:[,.]\\d+)*", "\"$0\""));


" "hello": "0", "zulu": "1,234", "Bravo": "987.456" "

Also, your expected result seems to be missing the doublequote and space that you have in the start of input string and that should most likely be a typo.