Reputation: 1782
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?
Upvotes: 2
Views: 73
Reputation: 18357
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.
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.
Upvotes: 4