Ann
Ann

Reputation: 206

How to write repeating Regex pattern in JavaScript

How to write a regex for the following pattern in JavaScript:

1|dc35_custom|3;od;CZY;GL|2;ob;BNP;MT|4;sd;ABC;MT|5;ih;DFT;FR|6;oh;AQW;MT|7;ip;CAN;MT|8;op;CAR;MT|9;ec;SMO;GL|10;do;CZT;KU|

where

The 1st character in it ranges from 2-11 and should not repeat. For example 3 appears in the first pattern, so should not appear again.

Upvotes: 0

Views: 331

Answers (2)

Mario
Mario

Reputation: 1359

A bit tricky, but here you go

The regex: /^1\|dc35_custom(?:\|([2-9]|1[01]);[a-z]{2};[A-Z]{1,3};[A-Z]{1,2}){9}\|$/

and the Unit tests: https://regex101.com/r/lU6sJ6/2 (hit 'Unit Tests' on the left)

I assume the following:

  1. the first group WILL ALWAYS BE THE SAME
  2. The first part of the pattern 3;od;CZY;GL is a number between 2-11 and NO NUMBER CAN REPEAT
  3. The second part is lowercase letters a-z, exactly two of them
  4. The third part is uppercase letters A-Z, between 1 and 3 ( the {1,3} thing, you can change it to {3} if it's exact)
  5. The fourth and last part is between 1 and 2 uppercase letters A-Z

Upvotes: 0

Colin P. Hill
Colin P. Hill

Reputation: 422

I'm making a lot of assumptions with this, but here's a crack at it:

1\|dc35_custom\|(([2-9]|10|11);[a-z]{2};[A-Z]{3};[A-Z]{2}\|){9}

How it works

  • 1\|dc35_custom\| is just literal text, escaping the vertical bar operators
  • ([2-9]|10|11) will match any number from 2 to 11.
  • [a-z]{2} will match two lowercase letters
  • [A-Z]{3} will match three uppercase letters
  • [A-Z]{2} will match two uppercase letters
  • {9} looks for nine consecutive matches of the entire sequence enclosed in parentheses

It will not, as Amadan points out, check for uniqueness, because that's a bit beyond what regex is for.

Upvotes: 2

Related Questions