Regular expression for Dutch zip / postal code

拈花ヽ惹草 提交于 2020-11-30 06:28:40

问题


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})$/;

回答1:


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



回答2:


Here is my solution. The i in the end makes it case-insensitive:

var rege = /^\d{4} ?[a-z]{2}$/i;



回答3:


In case you have trouble using this as pattern for bootstrap validation I suggest you change it to:

    ^[1-9][0-9]{3} ?(?!sa|sd|ss|SA|SD|SS)[A-Za-z]{2}$

This way it is still case-insensitive and accepted by the bootstrap validator.



来源:https://stackoverflow.com/questions/17898523/regular-expression-for-dutch-zip-postal-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!