Hein Hein - 7 months ago 14
PHP Question

Regular Expression German ZIP-Codes

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)

Answer

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.)

Comments