如何编写匹配引号内非空非空白字符串的正则?现有正则存空匹配问题
Hey there! Let's tackle your regex problem. Your current pattern var regex = new Regex("\"([^\"]+)\"") has a small gap: while it won't match empty quotes ("") thanks to the + quantifier, it will match quotes filled only with whitespace (like " " or "\\t\\n") because whitespace characters aren't excluded by [^"].
The Solution: Regex That Ensures At Least One Non-Whitespace Character
We need to modify the regex to guarantee that the content inside the quotes has at least one non-whitespace character. Here's a robust, easy-to-understand implementation:
var regex = new Regex(@"\""(?=[^\"]*\S)[^\"]*\""");
Breakdown of the Pattern
Let's break down each part to see how it works:
\"": Matches the opening double quote (we use C#'s verbatim string@to avoid messy escape character headaches)(?=[^\"]*\S): A positive lookahead that checks if there's at least one non-whitespace character (\S) somewhere inside the quotes before the closing quote.[^\"]*matches any number of non-quote characters leading up to that non-whitespace.[^\"]*: Matches all characters inside the quotes (including whitespace, but only if there's at least one non-whitespace present, thanks to the lookahead)\"": Matches the closing double quote
What It Matches & Doesn't Match
- ✅ Matches:
"hello world"," test ","a\tb\nc","mix of spaces and text" - ❌ Doesn't Match:
""," ","\\t\\n"," "
Handling Edge Cases (Optional)
If your use case includes escaped quotes inside the string (e.g., "He said \"Hello!\""), you'll need to adjust the regex to ignore escaped quotes. Here's the modified version:
var regex = new Regex(@"\""(?=(?:\\.|[^\"\\])*\S)(?:\\.|[^\"\\])*\""");
This version uses (?:\\.|[^\"\\]) to match either an escaped character (like \") or any non-quote, non-backslash character, ensuring escaped quotes don't break the match.
内容的提问来源于stack exchange,提问作者Kseniya Yudina

