Home > Enterprise >  Python regex to match street name and house number
Python regex to match street name and house number

Time:11-22

I have a regex which matches street names (see demo 1) and I have a regex which matches possible house numbers in Germany (see demo 2). Each regex works perfectly fine. In the next step I want to combine both regex (street names house number). In other words, I am looking for a regex which matches both street names and house numbers together.

I have prepared a demo 3 with examples. I know these examples are not complete if you compare it with the strict rules here, but it is enough for my use case.

Since regex is a rule based language, let me try to explain the rules in words:

  • In Germany the street name can be basicaly every kind of name. There can be a . or - in between.
  • The regex should match even with lower case characters
  • The house numbers are in most cases sth. like 99 or 99a. But I tried to be creative and added some additional possible examples

My problem: I have solutions to each seperate case (see demo 1 and 2) but my problem is that I don't know how to combine two regex to one (see demo 3).

Working regex for street names:

^(?:[A-Z] \d|[^\W\d_]{2,}\.?)(?:[- '’][^\W\d_] \.?)*$

Working regex for house numbers:

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

Based on the regex shown above, how do I combine both of them in order to match my examples shown in demo 3?

CodePudding user response:

Combining 2 regex into one:

^(?:[A-Z] \d|[^\W\d_]{2,}\.?)(?:[- '’][^\W\d_] \.?)*\s [1-9]\d{0,3} ?[a-zA-Z]?(?: ?[/-] ?[1-9]\d{0,3} ?[a-zA-Z]?)?$

Updated RegEx Demo

  • Related