0

I'm quite new to regex and trying to write a regular expression that matches the ZIP codes in each state, but having a hard time. As an example, Alaska has ZIP codes between 99501 and 99950, but this doesn't work:

99(5|6|7|8|9)(0|1|2|3|4|5|6|7|8|9)(0|1|2|3|4|5|6|7|8|9)

because it also matches 99951. Anyone done this already, or mind helping me out with at least the pattern for this? Here are the ZIP code ranges for each state: http://www.structnet.com/instructions/zip_min_max_by_state.html

Ben
  • 68,572
  • 20
  • 126
  • 174
Brian
  • 23
  • 3
  • duplicate: http://stackoverflow.com/questions/2577236/regex-for-zip-code – Zach Leighton Dec 05 '14 at 20:22
  • 1
    I'm not good enough with regexp's to give you an answer, but it sounds like you could use lookahead's to solve your problem. [reference here](http://www.regular-expressions.info/lookaround.html) It will proably be a huge pain to write as many of these as you'll need. You may have better luck finding an api to validate the zipcodes for you. – MIke Dec 05 '14 at 20:22
  • @MikeN: an API .. or a simple numerical comparison. – Jongware Dec 05 '14 at 20:23
  • possible duplicate of [What is the ultimate postal code and zip regex?](http://stackoverflow.com/questions/578406/what-is-the-ultimate-postal-code-and-zip-regex) – Alex A. Dec 05 '14 at 20:26
  • @Brian: you can also test your RegEx [here](http://regexpal.com). I use this site to refine the regex and prevent unwanted matches. They also provide a (short) summary of the most important keywords (e.g. \d to match any digit) – GameDroids Dec 05 '14 at 20:28
  • @Jongware hmmmm, I'm not sure a 'simple numerical comparison' can help when you have to take state codes into account, then considering states add zipcodes as populations change, I don't think OP will want to always be watching for things like that so he can redeploy his solution. By using a maintained API he does not have to worry about these factors. – MIke Dec 05 '14 at 20:31
  • I don't believe this is a duplicate of the ultimate postal code and ZIP question, since I'm not trying to validate any ZIP code, but rather match a specific range. As for using an API, I'm doing this through the GUI of a custom CMS, and don't have the option to use any method besides regex. – Brian Dec 08 '14 at 13:55

1 Answers1

1

regexp is a poor choice for that problem but I think this one might get the job done:

99(5(0[1-9]|[1-9]\d)|[6-8]\d\d|9([0-4]\d|50))

http://rubular.com/r/Fs9bTpgGTT

davidrac
  • 10,723
  • 3
  • 39
  • 71