Search code examples
regexvalidation

Regex for house number


Looking for a regex that specifies a German house number:

Valid house number:

  • 12
  • 12a
  • 12A
  • 12 A
  • 12 a
  • 12 b
  • 12 z
  • 121 b
  • 56/58
  • 56/58a
  • 56-58
  • 56 - 58
  • 56-58a

Not valid house number:

  • 25-ab
  • 12ü
  • 12_
  • 12!"§$$%&/()
  • a2
  • a2
  • 13àâäèéêë
  • 0
  • 123aaa123,
  • 123 aaa 123
  • 1 a 1
  • 1a 1
  • 1a1
  • 00 a
  • a a
  • 00a
  • 13àâäèéêëîïôœùûü

Only valid characters are: abcdefghijklmnopqrstuvwxyz

My regex doesn't match the way it should:

^[1-9]\d*(?:[ -]?(?:[a-zA-Z]+|[1-9]\d*))?$

Please see my example on regex101


Solution

  • A few notes about the pattern that you tried:

    • The pattern gets 1 match too many as [a-zA-Z]+ matches 1 or more times.
    • The pattern is not matching some values because this part [ -]? optionally matches a space or a hyphen and the / is not present in the character class
    • This part 56 - 58 will not match as there is a space and a hyphen to be matched and the optional character class [ -]? will match only one of those
    • This part 56-58a will not match, as there are no digits matched before the character class [a-zA-Z]

    As an alternative, a bit shorter variant than I initially commented using an alternation and the case insensitive flag:

    ^[1-9]\d*(?: ?(?:[a-z]|[/-] ?\d+[a-z]?))?$
    

    In parts

    • ^ Start of string
    • [1-9]\d* Match a digit 1-9 and optional digits 0-9
    • (?: Non capture group
      • ? Match an optional space
      • (?: Non capture group (for the alternation)
        • [a-z] Match a char a-zA-Z (using case insensitive match enabled)
        • | Or
        • [/-] ? Match either / or / with optional space
        • \d+[a-z]? Match 1+ digits with optional char a-zA-Z
      • ) Close non capture group
    • )? Close non capture group and make it optional
    • $ Assert end of line (Or use \Z if there can not be a newline following)

    Regex demo