You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写匹配引号内非空非空白字符串的正则?现有正则存空匹配问题

Fixing Regex to Match Non-Empty, Non-Whitespace-Only Quoted Strings

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:03:09