借助Regexr匹配对象数组键值对,修复无效JSON格式问题
Hey there! Let's figure out why your regex only matches one instance and fix that wonky JSON you're working on.
First, let's break down what's off with your original regex: \\"(.*)\\":"(.*)"
- The
.*is a greedy matcher—it grabs as much text as possible between the first\"and the last":"in your string, which is why you're only getting one match instead of multiple. - Also, this regex is targeting already escaped quotes (
\"), but you need to find the unescaped ones that are breaking your JSON lint check.
Let's adjust the regex based on your goal:
Your end goal is valid JSON like {"invert_lightness":"true"}, so I assume your malformed JSON has unescaped quotes inside values, or missing proper wrapping around keys. Here are two common scenarios and fixes:
Scenario 1: Unescaped quotes inside string values
If your JSON looks like this (note the unescaped quotes in the value):
{"invert_lightness":"it's "true" in dark mode"}
Use this regex to escape any " that aren't part of the JSON structure:
- Regex pattern:
(?<!\\)"(?!:|,|{|}) - Replacement:
\\" - How it works:
(?<!\\): Negative lookbehind—ensures the quote isn't preceded by a backslash (skips already escaped quotes)": The unescaped quote we want to target(?!:|,|{|}): Negative lookahead—ensures the quote isn't a structural one (like after a key, before a comma, etc.)
Scenario 2: Missing quotes around keys
If your JSON looks like this (keys aren't wrapped in quotes):
{invert_lightness:"true"}
Use this regex to add quotes around unquoted keys:
- Regex pattern:
(\w+)(?=:) - Replacement:
"$1" - How it works:
(\w+): Matches word characters (the key name)(?=:): Positive lookahead—only matches if the word is followed by a colon (so we target valid keys)
Quick testing tips for regexr
When you test these patterns:
- Make sure to enable the global flag (
g) so it matches all instances instead of just the first one - Double-check the replacement string—regexr handles
\\"correctly for escaping, but some tools require double-escaping (like\\\\"), so adjust if needed.
内容的提问来源于stack exchange,提问作者user9366125

