【问题标题】:RegEx for matching yaml files用于匹配 yaml 文件的正则表达式
【发布时间】:2019-05-31 17:19:04
【问题描述】:

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

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

等等。

如何匹配所有在 test/ 目录中但不在 test/test1/dev.yaml 等子目录中的 yaml 文件

我正在尝试使用 globing:

test/*.yaml 

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

我怎样才能实现它?

【问题讨论】:

  • 您使用的是 shell globbing 还是正则表达式?

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


【解决方案1】:

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

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

正则表达式电路

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

【讨论】:

  • 您应该使用+ 量词而不是*。 +1
  • 很好的答案@Emma。
猜你喜欢
  • 1970-01-01
  • 2018-03-09
  • 2017-06-24
  • 2010-10-10
  • 2011-05-15
  • 2013-02-11
  • 1970-01-01
相关资源
最近更新 更多