javascriptregexstringmatch

Regex to match if it contains same character 0 or 2 or 4 times next to each other


I need to create regex rule to match this kind of strings (the looking letter is 'a'):

but not:

Tried with [a]{2}|[a]{4} but this wasn't working. Any idea?


Solution

  • /^[^a]*(?:aa){0,2}[^a]*$/
    
    1. We need ^ and $ to match the whole string.
    2. The [^a]* match any number of non-as. This makes sure only the middle part contains as.
    3. (?:aa){0,2} matches zero aas (= empty), one aa (= aa) or two aas (= aaaa).

    >>> ['aa', 'aaaa', 'aabb', 'aaaagg', 'cccaazz', 'dddaaaazz', 'aaa', 'aaaaa', 'abb', 'bbbaaa', 'bbaazza']
        .map(c => `${c}: ${/^[^a]*(?:aa){0,2}[^a]*$/.test(c)}`).join('\n')
    "aa: true
    aaaa: true
    aabb: true
    aaaagg: true
    cccaazz: true
    dddaaaazz: true
    aaa: false
    aaaaa: false
    abb: false
    bbbaaa: false
    bbaazza: false"