Iranian postal code validation
Asked Answered
Y

1

28

Please, I need to validate Iranian postal code using regex. I write this regex for this case \b([^02\n\D]){4}[^5](\d){5} but its not working on rule number 5 and 7. please help me to fix it.

this is some rules about this regex:

  1. It's all numeric

  2. 10 digit count

  3. don't use 0 in first 5 digit

  4. don't use 2 in postal code

  5. First 4 digit is not the same

  6. The 5th digit cannot be 5

  7. all digits aren't the same

Yellowlegs answered 10/2, 2018 at 10:36 Comment(4)
In particular add an MCVE and detail the rules with samples of what does match or not.Varicelloid
This seems not to be a job for RegEx after allDistemper
Don't count on fourth rule! Many postal codes have 2 in different positions!Registration
@AliHosseinzadeh you're right here with an update without checking 2 in postal code: ^(?!0)\d(?!([0-9])\1{3})[1-9]{3}[1346-9][013-46-9][1-9](?!\1{8})\d$Yellowlegs
U
33

The following regex satisifes your conditions:

\b(?!(\d)\1{3})[13-9]{4}[1346-9][013-9]{5}\b

Click for Demo

Explanation:

  • \b - a word boundary
  • (?!(\d)\1{3}) - negative lookahead to make sure that the 1st 4 digits are not the same.
  • [13-9]{4} - matches 4 occurrences of all the digits except 0 and 2
  • [1346-9] - matches a single digit that is not a 0,2 or 5
  • [013-9]{5} - matches 5 occurrences of all the digits except 2
  • \b - a word boundary
Unproductive answered 10/2, 2018 at 11:6 Comment(6)
I'm really sorry but I read some article about Iranian postal code and that seems 0 can be in the second 5 digit but it can not be in first 5 digits, I fix my questionYellowlegs
@Yellowlegs I have updated the solution. Also, check the demoUnproductive
(?!(\d)\1{3}) - negative lookahead to make sure that the 1st 3 digits are not the same.Antefix
I know this is an old question, but it came up in the Reopen queue. This is a very slick answer, but I'd argue that any RegEx that needs 7 bullets to explain will be difficult to maintain, especially if somebody else gets tasked with doing so.Cheviot
@WonkotheSane The explanation was needed keeping in mind the different kind of audiences. I try to give an elaborate answer as much as possible, irrespective of its complexity, so that there is less to-and-fro communication in the comments section. :)Unproductive
@GurmanjotSingh - I absolutely agree. I just know that when I come across code that someone has written an elaborate RegEx for, I curse under my breath. :)Cheviot

© 2022 - 2024 — McMap. All rights reserved.