2
votes

I'm looking for a regex pattern which can do this exactly.

  1. Should match the length which is 12 characters alphaNumeric
  2. Should also check for the occurrence of hyphen - twice in the word
  3. No spaces are allowed.

I have tried the following regex:

^([a-zA-Z0-9]*-[a-zA-Z0-9]*){2}$

Some sample cases

-1234abcd-ab

abcd12-avc-a

-abcd-abcdacb

ac12-acdsde-

The regex should match for all the above.

And should be wrong for the below

-abcd-abcd--a

abcd-abcdefg

I've been using this regex ^([a-zA-Z0-9]*-[a-zA-Z0-9]*){2}$ for matching the above patterns, but the problem is, it doesn't have a length check of 12. I'm not sure how to add that into the above pattern. Help would be appreciated.

1
please post the pattern you have tried so far.Code Maniac
I've tried multitudes of regexes which are not working. I've gone through regexr and tried out all the combinations I know. But was of no use. @CodeManiaccapt.swag
can you post them, will help us to answer exactly what you were missing and also help you to learn too at the same timeCode Maniac
^([a-zA-Z0-9]*-[a-zA-Z0-9]*){2}$ This can be used to find a pattern with double hyphens, but I've no idea how to find the limit the overall length to 12 @CodeManiaccapt.swag
the easiest thing you can do in any language is check the length of string, str.length <= 12, if you want to do using regex you can use positive lookahead (which i will not suggest to use just for length restriction ), i.e (?=^.{12}$)Code Maniac

1 Answers

2
votes

Use this:

(?=^.{12}$)(?=^[^-]*-[^-]*-[^-]*$)[a-zA-Z0-9-]+ /gm

The first positive lookahead asserts the total length to be 12. The second positive lookahead asserts the presence of exactly two hyphens. Rest is just matching the possible characters in the character set.

Demo