2

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 keys, and I would like to replace the double-quotes surrounding alll the values 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.

2 Answers 2

6
String str = "\"lang\":\"fr\",\"fizz\":\"1\",\"buzz\":\"Thank you so much.\"";
System.out.println(str.replaceAll ("\"([^\"]*)\":\"([^\"]*)\"", "$1:'$2'"));
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.