Add pattern to regex for German house number system

Viewed 126

I have a Python regex for German house numbers which works okay. However, some pattern doesn't match as you can see in this demo.

These should be valid:

  • 56/58a
  • 18a - 19b
  • 18a-19b

This should not be valid (because the number of digits is too long):

  • 12345

This is my regex: ^[1-9]\d*(?: ?(?:[a-zA-Z]|[/-] ?\d+[a-z]?))?$

1 Answers

You can use

^[1-9]\d{0,3} ?[a-zA-Z]?(?: ?[/-] ?[1-9]\d{0,3} ?[a-zA-Z]?)?$

See the regex demo.

Details

  • ^ - start of string
  • [1-9]\d{0,3} ?[a-zA-Z]? - a non-zero digit, then zero to three digits, then an optional space and then an optional letter
  • (?: ?[/-] ?[1-9]\d{0,3} ?[a-zA-Z]?)? - an optional sequence of an optional space, / or -, an optional space and, like the part explained above, a non-zero digit, then zero to three digits, then an optional space and then an optional letter
  • $ - end of string.
Related