1

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

  • Show some examples that should pass and some that shouldn't. – acdcjunior Mar 13 '18 at 23:08
  • 12A31-A43 , 123-A1a15, 12345-ASD, NP-12345, NP 12345, 1235 234, ultimately it is alphanumeric which is atleast 5 character length, and atmost 10, may have one of either space or hyphen in the middle, number of characters before or after space/hyphen is not important – Abhishek Kakkerla Mar 13 '18 at 23:21
  • i could only make one of the criterias work separately but not in the combined regex as given in my post – Abhishek Kakkerla Mar 13 '18 at 23:23
  • 1
    Maybe something like `^(?=[^- ]*[- ][^- ]*$)[A-Za-z\d][A-Za-z\d -]{4,9}[A-Za-z\d]$` – CAustin Mar 13 '18 at 23:36
  • @CAustin Thanks Austin, this works well with one space/hyphen in middle. but if space/hyphen is removed then it's not working – Abhishek Kakkerla Mar 13 '18 at 23:48
  • @CAustin i tweaked your solution a bit, ^(?=.{5,10}$)(?=[^- ]*[- ]{0,1}[^- ]*$)[A-Za-z\d][A-Za-z\d -]{4,9}[A-Za-z\d]$ ... this is working in a scenario where no space/hyphen is required. Thanks again – Abhishek Kakkerla Mar 13 '18 at 23:50
  • @AbhishekKakkerla If you put `{0,1}` after the `[- ]`, it will allow patterns that do not contain any space or hyphen in the middle. Not sure if that was your intention. If so, note that `{0,1}` is synonymous with simply writing `?`. – CAustin Mar 14 '18 at 00:02
  • yes @CAustin, i was also thinking of this scenario too to include in my requirements. Thanks again – Abhishek Kakkerla Mar 14 '18 at 00:09

2 Answers2

1

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.)
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
0

after reading the posts from @acdcjunior and @CAustin, I corrected my solution too based on the regex they provided ...

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

this has more criteria than what i initially posted ... 1. limit a minimum of 3 to the left of space/hyphen which not mandatory 2. limit a maximum of 7 to the right of space/hyphen 3. overall the length should be 5 to 10 4. should be alphanumeric

hope this helps to someone else too.

Thank again.