RegEx fo replacing numbers in a string

Tal Angel :

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?

Pushpesh Kumar Rajwanshi :

You can capture the numbers using this regex,

\d+(?:[,.]\d+)*

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\""));

Prints,

" "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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=90905&siteId=1