Looking for a regex that specifies a German house number:
Valid house number:
Not valid house number:
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
A few notes about the pattern that you tried:
[a-zA-Z]+
matches 1 or more times.[ -]?
optionally matches a space or a hyphen and the /
is not present in the character class56 - 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 those56-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)