Regular Expressions

nibsy

Regular
Joined
Aug 7, 2002
Messages
51
Location
Kent, UK
I am trying to validate an English postcode of the form XXXX XXX using regular expressions.

I think I may have something wrong with my pattern. I am new to regular expressions and would appreciate if somebody could point out any glaring errors.

Visual Basic:
Dim pattern As String = "^\s*(\d{4}\s+\d{3})\s*$"
If Not Regex.IsMatch(txtPC.Text, pattern) Then
     ' Do Stuff
End If
[\VB]

Thanks in advance.
 
I don't know what the Input looks like (whether the postcode is between other words or not) but try it without the "^" and "$"... another point: the "Not" in you If-Clause... was that an accident? ;) or did I just not understand what you're trying to do? :D

Andreas
 
I'm not sure of the English format, but in the US the last 4 digits (not 3) are optional. If the last 3 are optional, you could change the expression.

Otherwise, it looks good. Personally, I'm not sure I'd want the "\s*" portions, as you'll have to manually trim off the whitespace to see the "real" data. I hate trimming, but it may be necessary for you. :)

-Nerseus
 
Thanks for the replies.

(Hamburger1984: The NOT in the IF clause only sets a boolean, as I intend to validate numerous input boxes :) )

Sorry, it appears I was testing the expression wrong!

Also, I needed to expand my expression somewhat to fully validate English post codes.

Here is the pattern I am using;

Visual Basic:
Dim pattern As String = "[A-Z]{1,2}\d{1,2}\s?\d[A-Z]{2}"
 
Last edited:
I just want to make sure you know that that pattern will match the following string:

...RUNDLL32 1ST PROBLEM I FORESEE...

It will match the "LL32 1ST" part of it

If you would like to make it a bit more robust, you might want:

\b[A-Z]{1,2}\d{1,2}\s{1,3}\d[A-Z]{2}\b

I'm not familiar with the English post codes, but are all of the following valid? These would all be caught by the expression

A1 2BC
DE3 4FG
H56 7IJ
KL89 0MN
 
Back
Top