uk postcode check regex

They have: 426 posts

Joined: Feb 2005

my regex knowledge is very basic, so I found this uk postcode check online. It works great except it checks for a space between the two sets of alphanumeric characters.
I want to stop it checking for the space but cant find the bit in this regex that does this. I thought it was the highlighted.

^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$

pr0gr4mm3r's picture

He has: 1,502 posts

Joined: Sep 2006

That is the part of the regex that checks for the space, but I'm pretty sure that if you remove the space, it's more than just taking that out.

I'm not familiar with UK postal codes. Can you describe in words what is being validated?

Also, try playing around with it here: http://regjex.com/ . I have found that tool helpful.

Greg K's picture

He has: 2,145 posts

Joined: Nov 2003

You should be able to replace the bold portion of the regex you gave with the following:

( ?)

This will have it let the space be optional.

A great tool I use for these is regex buddy. Until I bought (yeah, the B word, but well worth it), I used to have to look up anything but very basic expressions.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.