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

开发支持转义括号的正则表达式:匹配括号内任意内容

Solution for Parsing Escaped Parentheses Content

Let’s dive straight into a regex that meets your exact requirements—it’ll correctly capture content inside unescaped parentheses while ignoring escaped parentheses, backslashes, and letting special characters pass through unescaped:

^\((?P<content>(?:\\.|[^\\)])*)\)$

How This Regex Works

Let’s break it down piece by piece so you can tweak it if needed:

  • ^ and $: Anchor the regex to match the entire string (this prevents partial matches like extra trailing parentheses or incomplete expressions).
  • \(: Matches the opening unescaped parenthesis (we escape it with a backslash to treat it as a literal character).
  • (?P<content>...): A named capturing group to pull out the inner content (use a numbered group (...) if your regex flavor doesn’t support named groups).
  • (?:\\.|[^\\)])*: The core logic for valid inner content:
    • \\.: Matches any escaped sequence (a backslash followed by any character—this handles cases like \(, \\, or \@).
    • [^\\)]: Matches any character that’s not a backslash or closing parenthesis (so regular text and special characters like !£$%^&* don’t need escaping).
    • (?:...): A non-capturing group to bundle the two options, and * means match this pattern zero or more times.
  • \): Matches the closing unescaped parenthesis (the inner content pattern ensures this isn’t escaped).

Testing Against Your Examples

This regex works perfectly with your test cases:

  • Valid 1: (text) → Captures text
  • Valid 2: (1, 2, 3) → Captures 1, 2, 3
  • Valid 3: (one\(\\@) → Captures one\(\\@ (escaped sequences are preserved in the content)
  • Valid 4: ("!£$%^&*") → Captures "!£$%^&*" (special characters are allowed without escaping)

Rejects Invalid Cases As Expected

It will fail to match these error scenarios:

  • (text: Missing closing parenthesis → no match
  • (text\): Closing parenthesis is escaped → no unescaped ) to end the expression → no match
  • \(text): Opening parenthesis is escaped → regex expects an unescaped ( at the start → no match
  • (text)): Extra closing parenthesis → the regex matches up to the first ), but the trailing ) breaks the $ anchor → no match

Quick Implementation Note

If you’re using this in a programming language, remember to handle double-escaping where needed (e.g., in Python, use a raw string: r'^\((?P<content>(?:\\.|[^\\)])*)\)$'). If you need to find these expressions within a larger text (not just the whole string), remove the ^ and $ anchors—just be aware this could match multiple valid parenthetical groups.

Content of the question来源于stack exchange,提问作者user1275154

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:43:57