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

时间:2019-05-31 17:19:04

标签: regex string regex-negation regex-group regex-greedy

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

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

我该如何匹配完全在test /目录中但不在子目录(如test / test1 / dev.yaml)中的所有yaml文件

我正在尝试使用globing:

test/*.yaml 

但是它不适用于https://regex101.com/

如何实现?

1 个答案:

答案 0 :(得分:4)

在这里,我们将在test目录之后添加非斜杠char类条件以仅传递第一个目录,其表达式类似于:

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

如果愿意,我们可以添加/减少边界。例如,我们可以删除起点和终点锚点,但它可能仍然有效:

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}`);
    });
}

RegEx电路

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

enter image description here