kaaas
kaaas

Reputation: 73

Replacing some special characters between quotes

I want to replace dot and single apostrophe characters within a JSON string, ie only when quoted. Using this input:

String json = "{\"someJsonMap\":{\"with.dot.s\":1.0,\"'with.dots'.and.apostroph's.\":20.001}}";

I want to turn this:

{"someJsonMap":{"with.dot.s":1.0,"with.dots'.and.apostroph's":20.001}}

into this:

{"someJsonMap":{"withdots":1.0,"withdotsandapostrophs":20.001}}

I appreciate any help, solutions or explanations.

Upvotes: 0

Views: 1471

Answers (1)

Bohemian
Bohemian

Reputation: 425043

If there are never escaped quotes, then you use a look ahead for an odd number of quotes that follow. An odd number means you are inside quotes.

json = json.replaceAll("['.](?=(([^\"]*\"){2})*[^\"]*\"[^\"]*$)", "");

That trainwreck of a regex asserts that there's an odd number of quotes following by consuming multiples (0-n via *) of pairs of quotes ([^\"]*\"){2} with the remaining chars having only one quote [^\"]*\"[^\"]*$

If there are escaped quotes, you basically can't use regex.

Upvotes: 2

Related Questions