简体   繁体   中英

How to use .NET Regex.Match to Validate Postal/Zip Code Regular Expressions in Geonames Country Info Database

Greetings,

I'm using a local copy of the Geonames database, including the country-info data. My custom .NET application needs to validate the Postal/Zip codes that users input. The validation needs to be done locally and can not use the Geonames web services that are available. This is a requirement of my application. I'm hoping you can help me figure out how to do this.

Inside of the Geonames Country Info database there is a field that includes the regular expression to validate the Country/Zip code for the corresponding country. Here are the regular expressions that are contained in the data for both Canada and the USA:

Regexs in the Geonames database:

Canada: ^([a-zA-Z]d[a-zA-Z]d[a-zA-Z]d)$
USA: ^(d{9})$

In my application, once the validation is done I first identify the country that is selected and then I look up the valid postal code regex for the specific country. I then use the following .NET/C# code to test for a match:

bool testResult = Regex.IsMatch(postalCode, geonamesRegexForCountry);

When I enter valid sample data for the postal/zip codes, the regular expression match test always fails. Here are some valid values:

Canada:
   Postal Code: L5R3K6
   Postal Code: L8M1L5

USA:
   Zip Code: 35801
   Zip Code: 72201

The tests are always failing. Any idea why? Does the Geonames database use a different "regular expression syntax" than the .NET Regex.Match() function uses? Any suggestions on how to proceed from here?

I need to validate the postal/zip codes for all countries - not just Canada and the USA, so I'm really hoping I can leverage the wealth of content existing in the Geonames database!

Thanks for all of your help!

MomentSurfer

Perhaps it's just a formatting problem, but there are backslashes missing in your regexes:

Canada: ^([a-zA-Z]\d[a-zA-Z]\d[a-zA-Z]\d)$
USA: ^(\d{9})$

And, of course, they might not be matching your actual data. For example, the USA version only matches Zip codes like 123456789 ( exactly 9 digits) but not 12345 or 12345-6789 . And the Canada version likewise doesn't allow for any separators between the characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM