Regular Expression for Specific pattern with grouping based on length

Viewed 26

I'm trying to create a regular expression for a maximum of 20 characters in a group of 6 characters each separated by "-" i.e. ABCD12-DEFG34-HIJK89 in this pattern only.

so it should contain 3 groups of 6 alphanumeric characters separated by "-" and last group should contain only 6 characters. Tried below regular expression ^[A-Z0-9-]{20}$ but this only makes the regular expression to have alpha numeric character and "-" with max length of 20 characters. and then I tried ^([A-Z0-9]-{7})+([A-Z0-9]-{7})+([A-Z0-9]{6}){20}$ which is not working

is there a possibility to create regex with specific pattern?

1 Answers

You can use a "spelled out" regex like

^[A-Z0-9]{6}-[A-Z0-9]{6}-[A-Z0-9]{6}$

Or,

^[A-Z0-9]{6}(?:-[A-Z0-9]{6}){2}$

Details:

  • ^ - start of string
  • [A-Z0-9]{6} - six ASCII uppercase letters or digits
  • (?: - start of a non-capturing group:
    • - - a hyphen
    • [A-Z0-9]{6} - six ASCII uppercase letters or digits
  • ){2} - end of the non-capturing group, repeated twice
  • $ - end of string.

See the regex demo and the regex graph:

enter image description here

Related