This question already has answers here:
Regular expression for a string containing one word but not another
                                
                                    (4个答案)
                                
                        
                                9个月前关闭。
            
                    
我试图开玩笑地调整我的单元测试,而不是我的集成测试。它们与测试的组件一起位于相同的文件夹中。单元测试具有文件名模式* .test.js,其中*是组件名称。集成测试的格式为* .integration.test.js,其中*为组件名称。

我对Regex不好。我想出的最好的是:

(?!\bintegration\b)


这不包括所有集成测试,但是开玩笑现在正在尝试运行我的index.js文件。我需要表达式排除“集成”,但包括“测试”

最佳答案

我的猜测是,也许在这里我们可能想要一个类似于以下内容的表达式:

(?=.*\bintegration\b.*)(?!.*\btest\b.*).*


Demo



const regex = /(?=.*\bintegration\b.*)(?!.*\btest\b.*).*/gm;
const str = `integration, but include 'test'
integration, but include 'tes
integration, but include 'tests
.integration.test.js
.integration.tests.js`;
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}`);
    });
}

10-07 14:29