Here are a couple regular expressions for matching quote pairs in a string.
This pattern can be quite handy for attempting to fix malformed JSON.
' single quotesMatching all outer single quotes in a given string:
/(?:')(?=(?:[^']|'[^]*')*$)/gGiven this string:
echo $Rad;this is my string 'foo bar 'baz lol hi'The regex will only match 'foo + hi' & ignore the inner quote in 'baz (minus the words of course)
This is quite handy for trying to fix malformed JSON that contains single ' vs the required double "
const matchSingleQuotesRegex = /(?:')(?=(?:[^']|'[^]*')*$)/g
const malformedJSON = `{'lol': 'wh'atevr'}`
const fixedJSON = malformedJSON.replace(matchSingleQuotesRegex, '"')
console.log(fixedJSON)
/* Yay fixed */
// {"lol": "wh'atevr"}" double quotesMatching all outer double quotes in a given string:
/(?:")(?=(?:[^"]|"[^]*")*$)/gGiven this string:
this is my string "with stuff " in quotes"The regex will only match "with + quotes" & ignore the inner quote in stuff " in.
Usage in code:
const matchDoubleQuotesRegex = /(?:")(?=(?:[^"]|"[^]*")*$)/g
const original = `
newX {"lol": "whatevr"}
str {"lol": "hey"'there"}
`
const newStringWithSingleQuotes = original.replace(matchDoubleQuotesRegex, "'")
console.log(newStringWithSingleQuotes)
/*
newX {'lol': 'whatevr'}
str {'lol': 'hey"'there'}
*//(')((?:[^\\']*)(?:\\'[^\\']*)*)(')/gmhttps://regex101.com/r/rqJFrN/1 (old https://regex101.com/r/WWrRQF/1)