Bob
Bob

Reputation: 10775

groovy replace double quotes with single and single with double

I have a string "['type':'MultiPolygon', 'coordinates':[[73.31, 37.46], [74.92, 37.24]]]"

How can I replace all single quotes with double quotes and double to with single? The result should be like this: '["type":"MultiPolygon", "coordinates":[[73.31, 37.46], [74.92, 37.24]]]'

Upvotes: 2

Views: 9626

Answers (2)

hexin
hexin

Reputation: 977

From link given by @yate, you can find a method:

tr(String sourceSet, String replacementSet)

and apply that to your string as:

def yourString = ...
def changedString = yourString.tr(/"'/,/'"/)

that will do the job.

Upvotes: 4

Igor
Igor

Reputation: 33963

You want to use the replaceAll method. Since the first conversion will be overridden by the second, you may need a temporary variable:

String replacePlaceholder = '%%%' // Some unlikely-to-occur value
yourString = yourString.replaceAll('\'', replacePlaceholder)
    .replaceAll('"', '\'')
    .replaceAll(replacePlaceholder, '"')

It's certainly not the most efficient way to do it, but it's a start.

Upvotes: 1

Related Questions