Reputation:
I am being fed a string that looks like:
"lang":"fr","fizz":"1","buzz":"Thank you so much."
The real string is much long but follows this pattern of comma-delimited "key":"value"
pairs. I would like to strip out all the double-quotes around the key
s, and I would like to replace the double-quotes surrounding alll the value
s with single-quotes, so that my string will look like this:
lang:'fr',fizz:'1',buzz:'Thank you so much.'
My best attempt:
kvString = kvString.replaceAll("\"*\":", "*:");
kvString = kvString.replaceAll(":\"*\"", ":'*'");
System.out.println(kvString);
When I run this I get kvString
looking like:
"lang*:'*'fr","fizz*:'*1","buzz*:'*Thank you so much."
Can anybody spot where I'm going wrong? Thanks in advance.
Upvotes: 2
Views: 2191
Reputation: 17693
What you are wanting to do is to break the comma delimited string into a set of keyword value pairs using regex. Each of the comma delimited strings have the format of "keyword":"value" and what you want to do is transform this into keyword:'value'.
In order to do this you have to have regex remember the keyword and to remember the value and then in the output of the replaceAll to put those parts of the string back into another string.
This stackoverflow, non cpaturing group provides more information about groups. And this article also talks about grouping syntax.
Upvotes: 0
Reputation: 13900
String str = "\"lang\":\"fr\",\"fizz\":\"1\",\"buzz\":\"Thank you so much.\"";
System.out.println(str.replaceAll ("\"([^\"]*)\":\"([^\"]*)\"", "$1:'$2'"));
Upvotes: 6