简体   繁体   中英

Replace single quote with double quote with Regex

I have an app that received a malformed JSON string like this:

{'username' : 'xirby'}

I need to replaced the single quotes ' with double quoates "

With these rule (I think):

  • A single quote comes after a { with one or more spaces
  • Comes before one or more spaces and :
  • Comes after a : with one more spaces
  • Comes before one or more spaces and }

So this String {'username' : 'xirby'} or

{  'username' : 'xirby'  }

Would be transformed to:

{"username" : "xirby"}

Update:

Also a possible malformed JSON String:

{  'message' : 'there's not much to say'  }

In this example the single quote inside the message value should not be replaced.

Try this regex:

\s*\'\s*

and a call to Replace with " will do the job. Look at here .

Instead of doing this, you're better off using a JSON parser which can read such malformed JSON and "normalize" it for you. Jackson can do that:

final ObjectReader reader = new ObjectMapper()
    .configure(Feature.ALLOW_SINGLE_QUOTES, true)
    .reader();

final JsonNode node = reader.readTree(yourMalformedJson);

// node.toString() does the right thing

This regex will capture all appropriate single quotes and associated white spaces while ignoring single quotes inside a message. One can replace the captured characters with double quotes, while preserving the JSON format. It also generalizes to JSON strings with multiple messages (delimited by commas , ).

((?<={)\s*\'|(?<=,)\s*\'|\'\s*(?=:)|(?<=:)\s*\'|\'\s*(?=,)|\'\s*(?=}))

I know you tagged your question for java, but I'm more familiar with python. Here's an example of how you can replace the single quotes with double quotes in python:

import re
regex = re.compile('((?<={)\s*\'|(?<=,)\s*\'|\'\s*(?=:)|(?<=:)\s*\'|\'\s*(?=,)|\'\s*(?=}))')
s = "{   'first_name'   :   'Shaquille'     ,    'lastname'   :   'O'Neal'     }"
regex.sub('"', s)

> '{"first_name":"Shaquille","lastname":"O\'Neal"}'

This method looks for single quotes next to the symbols {},: using look-ahead and look-behind operations.

String test = "{'username' : 'xirby'}";
String replaced = test.replaceAll("'", "\"");

If you're looking to exactly satisfy all of those conditions, try this:

'{(\s)?\'(.*)\'(\s)?:(\s)?\'(.*)\'(\s)?}'

as you regex. It uses (\\s)? to match one or zero whitespace characters.

Concerning your question's tag is JAVA , I answered in JAVA .

At first import the libraries:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

Then:

Pattern p = Pattern.compile("((?<=(\\{|\\[|\\,|:))\\s*')|('\\s*(?=(\\}|(\\])|(\\,|:))))");
String s = "{   'firstName'   :   'Malus'     ,    'lastName'   :   ' Ms'Malus'     , marks:[   '  A+  ', 'B+']}";
String replace = "\"";
String o;

Matcher m = p.matcher(s);
o = m.replaceAll(replace);
System.out.println(o);

Output:

{"firstName":"Malus","lastName":" Ms'Malus", marks:["  A+  ","B+"]}

I recommend you to use a JSON parser instead of REGEX.

String strJson = "{  'username' : 'xirby'  }";
strJson = new JSONObject(strJson).toString();
System.out.println(strJson);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM