Reputation: 13
I need to use an expression in a string to look for a range of postcodes
The expression I already have works when the postcode has 5 numbers
e.g.
Postcode range 30000-39999
String USAPostcodeExp = @"^[0-3][0-9][0-9][0-9][0-9]$";
this works with the postcode 31234
but some of the postcodes have 5 digits a dash and 4 digits
e.g. postcode 31234-1234
and these are not been recognised from the script.
Only the first 5 digits are relevant to our needs
So how do I write it so either it accounts for the extra dash and 4 digits
OR it ignores anything after the 5th digit.
Upvotes: 1
Views: 42
Reputation: 71538
You can add a word boundary to your current regex instead of using a $
:
@"^[0-3][0-9][0-9][0-9][0-9]\b";
Also, you mentioned the range was 30000
to 39999
, so shouldn't that be:
@"^3[0-9][0-9][0-9][0-9]\b";
Instead?
Shortened to:
@"^3[0-9]{4}\b";
The above will do the second option: ignore everything after the 5th digit (but still ensure that it is a 5 digit code within the required range).
If you want to match the additional part, you can use an optional group:
@"^3[0-9]{4}(?:-[0-9]{4})?$";
Upvotes: 1