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

正则表达式优化需求:仅匹配括号内的A-D、+、'及括号,寻求修正

Fixing Your Regex to Enclose All Content in Parentheses

Got it, let's sort out this regex issue. Your original pattern ^[A-D\(\)\'+]+$ works for matching your allowed characters, but it doesn't enforce that every single character must live inside properly paired parentheses—which is why it's letting invalid stuff like A+B or (A slip through.

Here's the corrected regex that fits your exact requirements:

^(\([A-D'+]+\))+$

Let's break down what each part does, step by step:

  • ^ and $: These anchor the entire string, so we're checking from the very first character to the very last—no partial matches allowed.
  • (\([A-D'+]+\))+: This is the core rule, broken down further:
    • \(: Matches an opening parenthesis (escaped because parentheses are special regex characters that define groups).
    • [A-D'+]+: Matches one or more of your allowed inner characters: A-D, +, or '. The + here ensures the parentheses aren't empty (if you do need to allow empty parentheses later, swap this to *).
    • \): Matches a closing parenthesis to complete the group.
    • The outer + lets you chain multiple valid parenthetical groups, just like your example (A+B+C+D)(A+B)(A').

Valid Test Cases (Will Match):

  • ✅ (A+B+C+D)(A+B)(A') (your sample input)
  • ✅ (A')
  • ✅ (B+C)

Invalid Test Cases (Will Be Rejected):

  • ❌ A+B (no parentheses at all)
  • ❌ (A+B (unclosed opening parenthesis)
  • ❌ A+B) (unopened closing parenthesis)
  • ❌ (A+B)C (character outside parentheses)
  • ❌ () (empty parentheses, blocked by the inner +—remove if you need to allow this)

If you ever need to support nested parentheses (like ((A+B)C)), we'd need to adjust the regex to handle recursion, but based on your example, it looks like you're working with flat, non-nested groups, so this should solve your problem perfectly.

内容的提问来源于stack exchange,提问作者waterbottle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:36:57