-1

I have to validate a text value with RegEx for the following possible types of expressions: (must be 8 characters with 2 hyphens and 6 alphanumeric characters.)

  1. aa-99-99
  2. 99-23-bd
  3. 02-xx-04
  4. ab-99-cz
  5. sc-xd-49
  6. 99-xav-4
  7. 48-xyz-09
  8. 9-abc-01
  9. xs-899-x
  10. sss-99-x

I tried the following regex pattern but it didn't work:

/^(\d{1,3})-(\d{1,3})-(\d{1,3})$/
revo
  • 47,783
  • 14
  • 74
  • 117
sai
  • 55
  • 1
  • 7

2 Answers2

4

Update after OP's clarification:

If you'd like to only allow letter or numbers in each block, you may use:

^(?=.{8}$)(?:(?:[a-z]+|[0-9]+)(?:-|$)){3}

Demo.

If you also want to make sure the string contains both letters and numbers, you may use the following instead:

^(?=.{8}$)(?=.*[a-z])(?=.*[0-9])(?:(?:[a-z]+|[0-9]+)(?:-|$)){3}

Demo.


Original answer:

If I understand your requirements correctly, you may use something like this:

/^(?=.{8}$)[a-z0-9]{1,3}-[a-z0-9]{1,3}-[a-z0-9]{1,3}$/

Demo.

Breakdown:

^             # The beginning of the string.
(?=.{8}$)     # A positive Lookahead to limit the length of the string to exactly 8 chars.
[a-z0-9]{1,3} # One to three alphanumeric (English) characters.
-             # Matches the character "-" literally.
$             # The end of the string.

Update:

If you want to avoid repeating the [a-z0-9]{1,3} part, you may use something like this:

^(?=.{8}$)(?:[a-z0-9]{1,3}(?:-|$)){3}

...but the pattern will not be as easy to read so I would stick with the first one.


References:

2

Try the following regex with m flag on:

^(?=.{8}$)[^\W_]+(?:-[^\W_]+)+$

If you need to force a combination of both digits and letters use this:

^(?=.{8}$)(?![\d-]+$|[a-z-]+$)[^\W_]+(?:-[^\W_]+)+$

See live demo here

revo
  • 47,783
  • 14
  • 74
  • 117
  • It worked. Can you explain the regex how it checks the combinations – sai Jul 05 '19 at 18:57
  • Currently it seems that you have to modify your requirements to express what you really need otherwise we can't help you very well. – revo Jul 05 '19 at 19:04
  • No change in requirement, I'll give more clarity if you dint really understand. – sai Jul 05 '19 at 19:14
  • 8 digit which should have two minus i.e (min 1 to max3)-(min 1 to max3)-(min1 to max2) and the combination should be at least one alphabet or number combination not all alphabets or numbers i.e 00-aa-10 is valid , 00-00-00 , aa-aa-aa is not valid – sai Jul 05 '19 at 19:17
  • Your question doesn't include these or whatever else you may want to add later. Please edit your question. – revo Jul 05 '19 at 19:23