正则表达式双中括号不匹配:Discover信用卡正则分组转义求助
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}: Matches6011followed by 12 digits (total 16)64[4-9]\d{12}: Matches644-649followed by 12 digits (total 16)65\d{14}: Matches65followed 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

