Ryan H
Ryan H

Reputation: 2945

Regex pattern for London postcodes not matching

I'm trying to create a regex pattern for Javascript to test the provided postcode value to find out whether it matches a London postcode. London postcodes start with either:

My regex pattern is: ^[nN|eE|wW][1-9]{1}|[ecEC|wcWC|nw|NW|seSE|swSW]{2}, and for some reason it seems to think that a value starting with CE matches? when I haven't specified this...

Where am I going wrong here?

Upvotes: 1

Views: 66

Answers (1)

JvdV
JvdV

Reputation: 75840

Try something along these lines:

pattern = new RegExp('^(?:(?:n|e|w)[1-9]|(?:ec|wc|[ns]w|se))','gi')

See the online demo


After your comment I thought you might want to match exactly all the london postal district as per your link in OP.

pattern = new RegExp('^(?:e(?:[1-9]|1[0-8]|20)|n(?:[1-9]|1\d|2[012])|w(?:[1-9]|1[0-4])|ec[1-4]|wc[12]|nw(?:[1-9]|1[01])|se(?:[1-9]|1\d|2[0-8])|sw(?:[1-9]|1\d|20)) [a-z]+(?: [a-z']+)*$','gi')

See the online demo

You may have to double up the backslashes.

Upvotes: 1

Related Questions