正则表达式求助:匹配引号未包裹的冒号/逗号及引号数为4的记录
Got it, let's break this down step by step since you've been grinding on regex for 2 hours—nothing's more frustrating than when your pattern just won't catch what you need. Let's start with your core problems and work through each one:
First, let's fix your failed regex
Your current pattern [!^:"]|[^",] is actually matching almost every character (either !, ^, :, ", or anything that's not " or ,), which is why it's not targeting your broken records. We need to build patterns that target the structural issues instead of individual characters.
1. Locating the first and third broken records
Your problematic entries are:
"name":value"(first: missing quotes around value, extra trailing quote)"name":"value(third: missing closing quote for the value)
Here are targeted regexes to catch each:
- For the third record (unclosed value quote):
This matches lines starting with"name":"[^"]*$"name":"that don't have a closing"before the end of the line. - For the first record (no quotes around value, extra trailing quote):
This looks for"name":(?!")[^"]*"$"name":that isn't immediately followed by a quote, then any non-quote characters, ending with an extra quote. - Combine both into one pattern if you want to catch both in one search:
"name":(?!")[^"]*"$|"name":"[^"]*$
2. Matching scenarios where there's no quote before a colon or comma
No quote before a colon (unquoted key, e.g., name:"value")
To catch keys that aren't wrapped in quotes (so colon comes right after unquoted text):
[^"]+:"
This matches one or more non-quote characters immediately followed by :" (avoids matching colons inside quoted values like "name":"val:ue").
No quote before a comma (e.g., "name":value, or unclosed value with comma)
To catch commas that aren't preceded by a closing quote:
[^"],
This matches any non-quote character immediately followed by a comma, targeting cases where the value wasn't properly quoted before the trailing comma.
3. Finding records with exactly 4 quotes (your ideal "valid" record check)
A properly formatted entry like "name":"value" or "name":"value", has exactly 4 double quotes. Use this pattern to find those:
^(?:[^"]*"){4}[^"]*$
(?:[^"]*")= non-capturing group that matches any non-quote characters plus one quote{4}= repeat that group 4 times (so exactly 4 quotes)[^"]*$= match any remaining non-quote characters to the end of the line
That should cover all your use cases. Let me know if you need to tweak any of these for your specific data context!
内容的提问来源于stack exchange,提问作者deucalion0

