regular expression to add quotes for string values [closed]

I’m trying to add quotes for string values only in a file, for example:

String content = "ids:["123"],name:null,Quantity:8d-1,number:123,name:"hello",id2:"1234""; 

for ids, since it’s an array, so it’s fine. name is null so it’s also good. Quantity needs quotes on its value, number is good as its value is digit. So the expected output is

"ids:["123"],name:null,Quantity:"8d-1",number:123,name:"hello",id2:"1234""; 

I wrote

content.replaceAll(":([^"]+),", ":"$1",");

but which does not give me correct result. Any help is appreciated! Thanks

Answer

user8142520, the way you wrote it replaces everything that comes after name, and since the default is greedy, it gets the longest fit, which only happens at the comma after number.

The name field doesn’t fit your regex because of double quotes in it.

I’ve assumed that the Quantity field can have any pattern that can be separated from the content of other fields.

So I add y before your regex, to limit the replacing scope on the Quantity field and I’ve replaced in the regex [^"] for [^,], so the fit range doesn’t invade other field.

content.replaceAll("y:([^,]+),", "y:"$1",")

Leave a Reply

Your email address will not be published. Required fields are marked *