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

伊朗邮政编码正则验证求助:现有正则无法匹配规则5、7

Fixing Iran Postal Code Validation Regex

Let's break down your current regex issues and build a correct one that satisfies all 6 rules.

First, let's recap the official Iran postal code rules for clarity:

  1. Must be exactly 10 digits
  2. First 5 digits cannot be 0
  3. No digit in the code can be 2
  4. First 4 digits cannot all be identical
  5. 5th digit cannot be 5
  6. All 10 digits cannot be identical

Issues with Your Current Regex

Your regex \b([^02\n\D]){4}[^5](\d){5} fails to meet rules 4, 6, and has gaps in enforcing rules 2 and 3 for some positions:

  • It doesn't check if the first 4 digits are all the same (rule 4)
  • It doesn't block cases where all 10 digits are identical (rule 6)
  • The [^5] for the 5th digit allows non-digit characters (it should only allow valid digits excluding 0, 2, and 5 per rules 2, 3, and 5)
  • The final (\d){5} allows the digit 2, which violates rule 3

Corrected Regex

^(?!(\d)\1{9})(?!([13456789])\1{3})[13456789]{4}[1346789][013456789]{5}$

Breakdown of the Corrected Regex

Let's walk through each component to explain how it enforces every rule:

  • ^ & $: Anchor the regex to match the entire string (ensures exactly 10 digits, rule 1)
  • (?!(\d)\1{9}): Negative lookahead to block cases where all 10 digits are identical (rule 6)
  • (?!([13456789])\1{3}): Negative lookahead to ensure the first 4 digits aren't all the same (rule 4). The character set [13456789] ensures we only check valid digits for the first 4 positions.
  • [13456789]{4}: Matches the first 4 digits, allowing only 1,3,4,5,6,7,8,9 (enforces rule 2: no 0; rule 3: no 2)
  • [1346789]: Matches the 5th digit, allowing only 1,3,4,6,7,8,9 (enforces rule 2: no 0; rule 3: no 2; rule 5: no 5)
  • [013456789]{5}: Matches the last 5 digits, allowing 0,1,3,4,5,6,7,8,9 (enforces rule 3: no 2; rule 2 doesn't apply to the last 5 digits)

Quick Test Cases

To validate:

  • Valid code: 1346013460 (meets all rules)
  • Invalid (first 4 digits identical): 1111312345 → blocked by the second lookahead
  • Invalid (5th digit is 5): 1345513460 → blocked by the 5th digit character set
  • Invalid (all digits identical): 1111111111 → blocked by the first lookahead
  • Invalid (contains 2): 1346013260 → blocked by the last 5 digits character set

内容的提问来源于stack exchange,提问作者MasOOd.KamYab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:33:54