Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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.

 

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.

Posted

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

  • *Experts*
Posted

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

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Posted (edited)

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;

 

Dim pattern As String = "[A-Z]{1,2}\d{1,2}\s?\d[A-Z]{2}"

Edited by nibsy
Posted

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...