Search code examples
regexpostal-code

Two criterias and single regex for generic postal code


I created a regex for postal code (non us countries) to include two criterias ..

  • minimum 5 chars , max 10 chars
  • should have only alpha numneric with only one space/hyphen in the middle

regex: ^([a-zA-Z0-9]{3,10}[ |-]{0,1}[a-zA-Z0-9]{0,7})(.{5,10})$

I'm not sure where this is going wrong, but this is not working


Solution

  • How about:

    (?=^\w+[ -]\w+$)^[a-zA-Z0-9 -]{5,10}$
    

    Demo: https://regex101.com/r/xqMq7o/2

    Breakdown:

    • ^[a-zA-Z0-9 -]{5,10}$ sets the pattern for the allowed chars and size. It could be alone if it wasn't for the space/hyphen requirement
    • (?=^\w+[ -]\w+$) makes sure there's at least and at most one space/hyphen. (\w is OK to use because it includes a-zA-Z0-9 but not -. Alternatively, [^ -] could be used in its place.)