How to extract Dutch zip code with regex (Python)

Viewed 229

Assume I have the following list:

[4486AE Capelle aan de Ijsel, 4706TR Amsterdam]

I would like to extract the zip code for each element.

The desired output is:

[4486AE, 4706TR]

I tried to find a regular expression for Dutch zip codes in Python. However, I only found a JavaScript expression. This is what I tried so far:

import re

test = '4706TR Amsterdam'
match =  re.search(r"/^(?:NL-)?(\d{4})\s*([A-Z]{2})$/i", test)
print(match)

This gives me an empty result. Here is where I got the expression from: https://rgxdb.com/r/4W9GV8AC

Anyone has an idea how to solve this? Other SO posts do not focus on Python expression for Dutch zip codes.

1 Answers

The pattern that you tried /^(?:NL-)?(\d{4})\s*([A-Z]{2})$/i has a Javascript notation.

The leading and trailing / are the pattern delimiters, ^ and $ are the anchors to assert the start and end of the string and the /i flag is for a case insensitive match.

In Python, to get the match in your question you can match 4 digits and 2 uppercase chars A-Z between word boundaries \b to prevent partial matches instead of using the anchors as the matches are not the only string.

The case insensitive matches can be done using re.IGNORECASE

Using re.search can also return None, so first check if re.search has a value and then use .group() to get the match.

import re

test = '4706TR Amsterdam'
match =  re.search(r"\b\d{4}[A-Z]{2}\b", test, re.IGNORECASE)
if match:
    print(match.group())

Output

4706TR

See a Python demo

If you want to match an optional NL- part, the pattern can be:

\b(?:NL-)?\d{4}[A-Z]{2}\b

Regex demo

Related