Regular Expression German ZIP-Codes

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


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 ) {}

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

Edit: corrected, thanks to Hein.

Tags:

Php

Regex

Zip