user2521616 user2521616 -4 years ago 83
Javascript Question

Regexp in the Case of Single and Double Quotes

I have the following JavaScript:

let strTest = `
"The issue": "L'oggetto ",
"issue": "oggetto",
"issue": 'oggetto "novo" ',
`;


I'm trying to tokenize a string like the one above.

My regexp attempt:

let regExp = /["'](.*?)["']\s*?:\s*?['"](.*?)["']/gm;


This works fine, except in the case where I have a pair of single quotes (') inside of double quotes (") or vice-versa.

Is this possible with only one regular expression?

Answer Source

You can use backreferences:

/(["'])(.*?)\1\s*?:\s*?(['"])(.*?)\3/gm

This will include the quotes, in the tokenized string, but you can then remove them from the produced match by taking only the even numbered tokens.

Edit: As @TJ Crowder points out, this will not work correctly if the string contains escaped quotes in the form of \" within the string. In order to completely accommodate those escaped quotes and not break on strings like \\"(an escaped backslash preceding a quote) you will need to parse with multiple regexes or take a different tactic

The other thing you might want to look at, if this is coming from JSON, is ignoring regex, and just iterating through the properties of your json object. It depends if the string you're getting is coming in as valid json or not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download