user1768830
user1768830

Reputation:

Java regex replacing double and single quotes

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.

Upvotes: 2

Views: 2191

Answers (2)

Richard Chambers
Richard Chambers

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

Mikhail Vladimirov
Mikhail Vladimirov

Reputation: 13900

String str = "\"lang\":\"fr\",\"fizz\":\"1\",\"buzz\":\"Thank you so much.\"";
System.out.println(str.replaceAll ("\"([^\"]*)\":\"([^\"]*)\"", "$1:'$2'"));

Upvotes: 6

Related Questions