How to match zipcode for simple address matching regex?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dschu012
    New Member
    • Jul 2008
    • 39

    How to match zipcode for simple address matching regex?

    I am trying to make a regex to match simple addresses like

    123 Main Street
    Simpleville, VA 12345

    I have little experience with regex's and through reading and lots of messing around I have come up with.

    Code:
    /(\d{1,5}).*\b(A[LKSZRAP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])\b/gm
    While this can get many false positives it seems to work well enough in most cases since the state abbreviation has to be uppercase. The problem I am having it matching the zipcode too. What I did was attach \d{5}? to the end of that regex but that just caused the whole regex to fail. Shouldn't the ? mean that it will optionally match 5 digits if it sees them? Thanks.
  • Oralloy
    Recognized Expert Contributor
    • Jun 2010
    • 988

    #2
    dschu012,

    I don't see anything in your pattern looking for a zip code.

    Perhaps try adding something like this bit at the end of your pattern:
    Code:
     *[0-9]{5,5}(-[0-9]{4,4})?
    Which is to say:
    1. one or more spaces
    2. followed by five digits
    3. optionally followed by a hyphen and four additional digits


    Sorry if I'm a little old-school, I don't know all your requirements. If you look on CPAN, there are some really good (Perl) patterns for recognizing all sorts of things.

    For example, Geo::StreetAddr ess::US.

    Cheers!
    Oralloy
    Last edited by Oralloy; Jan 31 '11, 06:20 PM. Reason: Correct formatting of list.

    Comment

    • dschu012
      New Member
      • Jul 2008
      • 39

      #3
      Thanks. I got what I needed by adding
      Code:
      (\s+\d{5})?
      to the end. Previously I had the ? inside the parenthesis with was causing the regex to come back with nothing if there were no spaces after the state.

      Comment

      • Oralloy
        Recognized Expert Contributor
        • Jun 2010
        • 988

        #4
        Yep, much more concise.

        So you don't have to deal with nine-digit zip codes, then?

        Comment

        Working...