用于在先行后匹配多个事件的正则表达式

RegEx for matching several occurrences after lookahead

我在文本文件中得到以下段落:

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

我想将 (default) 之后的所有大写字母 (2-4) 都匹配到右括号,所以 AABBBCCCC 都匹配了。

这是我想出的,但它与 BBB:

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

那么在 (default) 之后匹配多个大写字母我缺少什么?

如果我们只想匹配问题中的模式,我们只需通过我们想要的案例并使用 (default) 使另一个失败:

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

Demo 1

或:

(?=\(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}`);
    });
}

正则表达式电路

jex.im 可视化正则表达式: