Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for Dutch zip / postal code

I'm trying to build a regular expression in javascript to validate a Dutch zipcode.

The zipcode should contain 4 numbers, then optionally a space and then 2 (case insensitive) letters

Valid values:

1001aa  
1001Aa  
1001 AA

I now have this, but it does not work:

var rege = /^([0-9]{4}[ ]+[a-zA-Z]{2})$/;
like image 250
Adam Avatar asked Jul 27 '13 13:07

Adam


People also ask

Is STR_detect regex for Dutch ZIP / postal code case sensitive?

I want to write a str_detect regex that only gives TRUE when there is a Dutch postal code (i.e., four digits first and two letters after. Non case sensitive). I also found this question before: Regular expression for Dutch zip / postal code.

What is a ZIP code used for?

ZIP codes are postal codes used in the United States, and are used with an address to describe the region that the address is located in. How do we write a regular expression that will match or validate a ZIP code?

How do you write a regular expression for a ZIP code?

A regular expression for ZIP codes needs to match 5 digits at the start, followed by 4 optional digits that further refine the region. The last 4 digits can be separated from the first 5 by a dash or space, or they can be written without any separator.

How many numbers should be in a ZIP code?

The zipcode should contain 4 numbers, then optionally a space and then 2 (case insensitive) letters Show activity on this post. Edited to handle no leading 0 requirement for Dutch postal codes, and to eliminate matches for SS, SA, and SD. This should do it all for you.


1 Answers

Edited to handle no leading 0 requirement for Dutch postal codes, and to eliminate matches for SS, SA, and SD. This should do it all for you.

Final regex:

var rege = /^[1-9][0-9]{3} ?(?!sa|sd|ss)[a-z]{2}$/i;

Fiddle unit test: http://jsfiddle.net/hgU3u/

Here's a breakdown:

  1. ^ matches beginning of string
  2. [1-9][0-9]{3} matches a single non-zero digit, and three 0-9 digits
  3. ? matches 0 or 1 spaces (you could use * to match 0 or more spaces)
  4. (?!sa|sd|ss) is a lookahead test to check that the remainder is not "sa", "sd", or "ss".
  5. [a-z]{2} matches 2 a-z characters
  6. $ matches the end of the string
  7. i at the end is the case-insensitive modifier
like image 181
Steven Moseley Avatar answered Oct 12 '22 16:10

Steven Moseley