regex for zip-code

前端 未结 3 1719
名媛妹妹
名媛妹妹 2020-11-28 03:39

Possible Duplicate:
What is the ultimate postal code and zip regex?

I need Regex which can satisfy all my thr

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 04:19

    I know this may be obvious for most people who use RegEx frequently, but in case any readers are new to RegEx, I thought I should point out an observation I made that was helpful for one of my projects.

    In a previous answer from @kennytm:

    ^\d{5}(?:[-\s]\d{4})?$
    

    …? = The pattern before it is optional (for condition 1)

    If you want to allow both standard 5 digit and +4 zip codes, this is a great example.

    To match only zip codes in the US 'Zip + 4' format as I needed to do (conditions 2 and 3 only), simply remove the last ? so it will always match the last 5 character group.

    A useful tool I recommend for tinkering with RegEx is linked below:

    https://regexr.com/

    I use this tool frequently when I find RegEx that does something similar to what I need, but could be tailored a bit better. It also has a nifty RegEx reference menu and informative interface that keeps you aware of how your changes impact the matches for the sample text you entered.

    If I got anything wrong or missed an important piece of information, please correct me.

提交回复
热议问题