Rbijker.com
Rbijker.com

Reputation: 3114

Regular expression for a zipcode with 4 digits and 2 optional letters

I need to check zip codes in JavaScript. The rule is 4 digits are mandatory and 2 letters at the end are optional. 1 space between the digits and the letters is also allowed.

Examples:

1019 //true
1019PZ //true
1019 PZ //true
1019P //false
(and anything else is false)

This is the regular expression I have so far. But in this regex the letters at the end are not optional but mandatory

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

Any suggestions to make the letters at the end optional?

Upvotes: 0

Views: 555

Answers (3)

Sami Farhat
Sami Farhat

Reputation: 1162

The following works:

\d{4} ?[A-z]{2}?
  • \d{4}: matches 4 mandatory digits
  • "space?": matches one optional whitespace between digits and letters
  • [A-z]{2}?: matches two optional letters

Upvotes: 0

Josh Crozier
Josh Crozier

Reputation: 240888

Group [a-z]{2} with a non-capturing group (?:[a-z]{2})? followed by ? in order to make the group optional. In doing so, two letters will be optional and you can't have just a single letter.

^[1-9][0-9]{3} ?(?!sa|sd|ss)(?:[a-z]{2})?$

Example Here

Upvotes: 4

Roman Makhlin
Roman Makhlin

Reputation: 993

For example You can try this one:

/^[1-9][0-9]{3} ?(?!sa|sd|ss)[a-z]{0,2}$/

Just add to a range a value of zero, which means that your letter can be present from zero to two times.

Upvotes: 0

Related Questions