Account for leading and trailing whitespace.

  • Thread starter Thread starter tim
  • Start date Start date
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.
 
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
 
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();
 
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
 
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+
 
: 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
 
Back
Top