Account for leading and trailing whitespace.

T

tim

I am new to Regular Expressions and need some assistance with my Zip
Code field validator. I am currently using the following regex to
validate a zip code:

^(\d{5}(( |-)\d{4})?)|([A-Za-z]\d[A-Za-z]( |-)\d[A-Za-z]\d)$

I would like to account for any number of leading and trailing
whitespace characters but am not sure how to do so. Thanks in advance
for your help.
 
R

Rad [Visual C# MVP]

I am new to Regular Expressions and need some assistance with my Zip
Code field validator. I am currently using the following regex to
validate a zip code:

^(\d{5}(( |-)\d{4})?)|([A-Za-z]\d[A-Za-z]( |-)\d[A-Za-z]\d)$

I would like to account for any number of leading and trailing
whitespace characters but am not sure how to do so. Thanks in advance
for your help.

Remove the ^, which indicates the string must begin with a digit and the $
which indicates the string must end with a digit and then give it a go
 
T

Tom Porterfield

I am new to Regular Expressions and need some assistance with my Zip
Code field validator. I am currently using the following regex to
validate a zip code:

^(\d{5}(( |-)\d{4})?)|([A-Za-z]\d[A-Za-z]( |-)\d[A-Za-z]\d)$

I would like to account for any number of leading and trailing
whitespace characters but am not sure how to do so. Thanks in advance
for your help.

What do you mean by "account for"? Do you want them to make the zip
invalid, or do you want to ignore them and only validate the actual
number/letters in the zip. If the latter, why not trim them off before the
validation:

string zipString = " 12345 ";
zipString = zipString.Trim();
 
P

Peter Bradley

Assuming the symbol for white space is \w (I may be wrong on this), I think
you just have to insert \w* at the start of your regular expression,
immediately after the ^, and the same again at the end immediately before
the $:

^\w*(\d{5}(( |-)\d{4})?)|([A-Za-z]\d[A-Za-z]( |-)\d[A-Za-z]\d)\w*$

HTH


Peter
 
R

Rad [Visual C# MVP]

Assuming the symbol for white space is \w (I may be wrong on this), I think
you just have to insert \w* at the start of your regular expression,
immediately after the ^, and the same again at the end immediately before
the $:

^\w*(\d{5}(( |-)\d{4})?)|([A-Za-z]\d[A-Za-z]( |-)\d[A-Za-z]\d)\w*$

Hey Peter,

The \w is actually for word characters. The white space one is \s

So what you want to indicate any number of spaces is \s+
 
G

Greg Bacon

: The \w is actually for word characters. The white space one is \s
:
: So what you want to indicate any number of spaces is \s+

Zero is still a number isn't it? :)

Use \s* to match any number of whitespace characters.

Greg
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top