-1

Is there a regex expression I can use to find all the numbers in JSON string and replace them within double quotes?

For example in the below JSON string, I want to replace the Id and Phone values with double quotes.

String jsonString = " [ 
{ 
   "FirstName": "abc",  
   "Email" : "[email protected]",
   "Id" : 1,
   "Phone" : 1234567890,
   "Date": "2 May 2016 23:59:59"

}, 
{  
   "FirstName": "xyz",  
   "Email" : "[email protected]",
   "Id" : 2,
   "Phone" : 9876543210,
   "Date": "3 May 2016 23:59:59" 

} 
] ";

I want to get the following output:

[ 
    { 
       "FirstName":"abc",  
       "Email" : "[email protected]",
       "Id" : "1",
       "Phone" : "1234567890",
       "Date": "2 May 2016 23:59:59"

    }, 
    {  
       "FirstName":"xyz",  
       "Email" : "[email protected]",
       "Id" : "2",
       "Phone" : "9876543210",
       "Date": "3 May 2016 23:59:59"  

    } 
    ] 

I tried line below but it does not work. Any ideas?

 jsonString = jsonString.replaceAll("=[ ]*([\\d]+)", "= \"$1\""); 

3 Answers 3

4

You are doing multiple things wrong.

  • Your regex searches for matches starting with a = instead of :
  • To capture white(space) use \s

Here is your correct regex: https://regex101.com/r/sRDXMP/2/

And here is your fixed code: jsonString = jsonString.replaceAll(":\\s([\\d]+)", ": \"$1\"");

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

2 Comments

Escaping the backslash itself is not an error, thats Java syntax (unfortunately)
@MichaelA.Schaffrath thanks, updated the code snippet.
1

Replace the = in your regular expression by :
Also, you should use the whitespace selector instead of [ ].

jsonString = jsonString.replaceAll(":\\s*(\\d+)", ": \"$1\"");

2 Comments

I also have a date object. so the : should not be replaced. i have edited my post again.
Then you just need to expect a comma or a right curly bracket after your digits: ":\\s*(\\d+)\s*[,}]"
0

i know its a little bit more typing but if you want to add the exact attributes you want to remove you can also use this regex

 (?<="tlv":")[^"]+(?=")

playground: regex

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.