Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression German ZIP-Codes

Tags:

regex

php

zip

I give up. I need a (PHP) regular expression that matches only 5 digit numbers starting from 01001 up to 99998.

So, invalid is for example 1234, but not 01234. Also 01000 is invalid, 01002 is not, and so on. Any other 5 digit number except 99999 is valid.

What I have is the following regular expression, which does what I require - except that it still matches 99999.

Can anyone help out? Thanks...

^01\d\d[1-9]|[1-9]\d{3}[(?<=9999)[0-8]|[0-9]]$

Update

I am sorry, everybody, but things are more complex. I did not explain correctly. German zip code can be also 04103 for example (see a list of some further examples here)

like image 293
Hein Avatar asked Oct 28 '11 08:10

Hein


3 Answers

You were close:

^0[1-9]\d\d(?<!0100)0|0[1-9]\d\d[1-9]|[1-9]\d{3}[0-8]|[1-9]\d{3}(?<!9999)9$

But if you can just do a simpler regex and then use a separate numerical comparison, that'd probably be easier to read.

Alternatively, a simpler version:

^(?!01000|99999)(0[1-9]\d{3}|[1-9]\d{4})$

(The simpler version is just "take the numbers 01000-99999 and remove the two ends via a lookahead.)

like image 155
Amber Avatar answered Oct 04 '22 08:10

Amber


The fastest way is just to check if string is made of 5 digits and then check if it is in specified range:

if ( preg_match('/^\d{5}$/', $input) && (int) $input > 1000 && (int) $input < 99999 ) {}
like image 37
hsz Avatar answered Oct 04 '22 06:10

hsz


\b(?!01000)(?!99999)(0[1-9]\d{3}|[1-9]\d{4})\b

Edit: corrected, thanks to Hein.

like image 25
Alexey Avatar answered Oct 04 '22 06:10

Alexey