Search code examples
javascriptregexregex-lookaroundsregex-groupregex-greedy

RegEx for matching several occurrences after lookahead


I got following passage in a text file:

(default) AA / BBB)
ASDF / XYZ / GE
(default) CCCC)

I want to match all uppercase letters (2-4) after (default) to the closing bracket, so AA, BBB and CCCC are matched.

This is what i came up with, but it doesn't match the BBB:

(?<=default\)\s)[A-Z]{2,4}

So what am I missing to match more than one group of uppercase letters after (default)?


Solution

  • If we wish to only match the pattern in the question, we would just simply pass our desired cases and fail the other one using (default):

    \(default\)(.+?([A-Z]{2,4}).+?([A-Z]{2,4})|.+?([A-Z]{2,4}))
    

    Demo 1

    or:

    (?=\(default\))(.+?([A-Z]{2,4}).+?([A-Z]{2,4})|.+?([A-Z]{2,4})).+
    

    Demo 2

    const regex = /\(default\)(.+?([A-Z]{2,4}).+?([A-Z]{2,4})|.+?([A-Z]{2,4}))/gm;
    const str = `(default) AA / BBB)
    ASDF / XYZ / GE
    (default) CCCC)`;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }

    RegEx Circuit

    jex.im visualizes regular expressions:

    enter image description here