cocacrave cocacrave - 3 months ago 6x
Javascript Question

Regex Find Pattern of 4 Characters

I'm confused how to do this.
I have an array of strings that match this pattern:


I'm hoping to use regex to figure out if a particular string matches one of these patterns. The strings themselves do not actually consist of A, B, or C. This is just to show how the pattern looks like. For example:
Pattern AAAB should not equal BAAA.

Can you help?

Edit - For example:

['TTES', 'TEES', 'TESS', 'TTTE', 'TEEE']

array[0] should match AABC,

array[1] should match ABBC,

array[2] should match ABCC,

array[3] should match AAAB,

array[4] should match ABBB,


You could generate RegExp from your patterns this way:

var stringToPattern = function (string) {
    var regexString = string.split('').map(function (char, position, string) {

        var prevIndex = string.indexOf(char);

        return prevIndex < position ? '(\\' + (prevIndex + 1) + ')' : '(.)';


    return new RegExp(regexString);

The function generates a regular expression based on the input string:

  • AABC to /(.)(\1)(.)(.)/
  • ABBC to /(.)(.)(\2)(.)/
  • etc...


stringToPattern('AABC').test('TTES'); // true
stringToPattern('AABC').test('TEES'); // false

stringToPattern('ABBC').test('TEES'); // true
stringToPattern('ABBC').test('TTES'); // false