用于匹配 yaml 文件的正则表达式

RegEx for matching yaml files

我有下一个包含 yaml 文件的目录路径:

test/1.yaml
test/dev.yaml
test/dev0_r.yaml 

我怎样才能匹配完全在 test/ 目录中但不在子目录中的所有 yaml 文件,如 test/test1/dev.yaml

我正在尝试使用 globing:

test/*.yaml 

但它在 https://regex101.com/

上不起作用

如何实现?

在这里,我们将在 test 目录后添加一个 non-slash char class 条件,以仅传递第一个目录,表达式类似于:

^test\/[^\/]+\.yaml$

我们可以 add/reduce 我们的界限,如果我们愿意的话。例如,我们可以删除开始和结束锚点,它可能仍然有效:

test\/[^\/]+\.yaml

Demo

const regex = /^test\/[^\/]+\.yaml$/gm;
const str = `test/1.yaml
test/dev.yaml
test/dev0_r.yaml
test/test1/dev.yaml`;
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 可视化正则表达式: