开发支持转义括号的正则表达式:匹配括号内任意内容
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)→ Capturestext - Valid 2:
(1, 2, 3)→ Captures1, 2, 3 - Valid 3:
(one\(\\@)→ Capturesone\(\\@(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

