capt.swag
capt.swag

Reputation: 10661

Regex pattern matching for contains a character

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.

Upvotes: 2

Views: 98

Answers (1)

CinCout
CinCout

Reputation: 9619

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

Upvotes: 2

Related Questions