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

正则表达式双中括号不匹配:Discover信用卡正则分组转义求助

Fixing Discover Credit Card Regex Issues: Bracket Mismatch & Length Validation

Let's break down your two problems and fix them step by step, with practical regex examples tailored to Discover card rules:

1. Resolving Double Bracket Mismatch Errors

Double square brackets [[...]] are invalid in regex syntax. Square brackets define a character set (matching any single character inside them), and nesting them doesn't create a logical group—it just treats the inner [ as a literal character, which throws off bracket balance.

Instead, use parentheses () to create groups for alternative starting patterns (like the different valid prefixes for Discover cards):

  • ❌ Wrong (causes mismatch): [[6011|64[4-9]|65]]
  • ✅ Correct: (6011|64[4-9]|65)

2. Proper Grouping & Length Validation

Discover cards require exactly 16 digits, with valid prefixes: 6011, 644-649, or 65. Here are two clean ways to enforce length while matching these patterns:

Option 1: Direct Length Calculation in Groups

Build the 16-digit requirement directly into each prefix pattern:

^(6011\d{12}|64[4-9]\d{12}|65\d{14})$
  • 6011\d{12}: Matches 6011 followed by 12 digits (total 16)
  • 64[4-9]\d{12}: Matches 644-649 followed by 12 digits (total 16)
  • 65\d{14}: Matches 65 followed by 14 digits (total 16)

Option 2: Positive Lookahead for Global Length Check

If you want to explicitly validate the total 16-digit length first (for readability), use a positive lookahead to enforce this rule before matching the prefix:

^(?=(?:\d{4}){4}$)(6011|64[4-9]|65)\d+$
  • (?=(?:\d{4}){4}$): The lookahead checks that the entire string is exactly 16 digits (four groups of 4 digits)
  • The main group (6011|64[4-9]|65) captures valid prefixes, and \d+ fills the rest (the lookahead ensures it adds up to 16 total)

Why Your Escape Attempts Failed

Escaping brackets with \[ wasn't the solution here—double brackets aren't a syntax that needs escaping; they're just incorrect usage. The fix is to replace nested square brackets with parentheses for logical grouping, not to escape characters unnecessarily.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 09:04:11