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

正则表达式需求:仅匹配指定中间两位数字的ID格式

Fixing Your ID Regex for Specific Middle Two Digits

Got it, let's sort out that regex issue for you. The core problem with your current pattern is how you're trying to match the middle -XX- segment—using square brackets [] here is wrong because they define a character set, not a set of full two-digit combinations. That's why it's matching any random two digits instead of your allowed values.

Let's Break Down the Fix

First, let's recap your requirements:

  • ID format: XXXXXX-XX-XXXX (6 digits, hyphen, specific two-digit code, hyphen, 4 digits)
  • Allowed middle codes: 01, 02, 21, 22, 23, 24

Option 1: Simplified Regex (If You Don't Need Strict 6-Digit Validation)

If the first 6 digits can be any numbers (no specific range rules), this clean pattern will work perfectly:

^\d{6}-(01|02|21|22|23|24)-\d{4}$
  • ^\d{6}: Matches exactly 6 leading digits
  • (01|02|21|22|23|24): Uses parentheses to group your allowed two-digit codes (the | means "or", so it only matches these exact combinations)
  • -\d{4}$: Matches the final hyphen plus 4 digits, anchored to the end of the string to prevent extra characters.

Option 2: Preserving Your Original 6-Digit Validation Rules

If you need to keep the strict rules for the first 6 digits (from your original regex: first two any digits, next two are 01-09 or 10-12, last two are 01-09, 10-29, or 30-31), we'll fix just the middle segment and simplify the redundant parts of your original pattern:

^[0-9]{2}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])-(01|02|21|22|23|24)-[0-9]{4}$
  • I cleaned up redundant syntax like [0-0]{1} → 0 and [1-1]{1} → 1 to make the regex easier to read
  • Replaced the broken [01|21|23|24|01]{2} with the correct grouped (01|02|21|22|23|24) to enforce your allowed middle codes.

Test Cases

✅ Matches valid IDs:

  • 880101-01-5332
  • 121231-24-1234
  • 990929-02-4321

❌ Rejects invalid IDs:

  • 880101-03-5332 (middle code 03 not allowed)
  • 880101-11-5332 (middle code 11 not allowed)
  • 88010-01-5332 (only 5 leading digits)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:16:32