伊朗邮政编码正则验证求助:现有正则无法匹配规则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:
- Must be exactly 10 digits
- First 5 digits cannot be
0- No digit in the code can be
2- First 4 digits cannot all be identical
- 5th digit cannot be
5- 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 digit2, 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 only1,3,4,5,6,7,8,9(enforces rule 2: no0; rule 3: no2)[1346789]: Matches the 5th digit, allowing only1,3,4,6,7,8,9(enforces rule 2: no0; rule 3: no2; rule 5: no5)[013456789]{5}: Matches the last 5 digits, allowing0,1,3,4,5,6,7,8,9(enforces rule 3: no2; 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
相关产品推荐
相关产品推荐

