【问题标题】:Node-Minimatch/Regex: Match subdirectories within a specified subdirectoryNode-Minimatch/Regex:匹配指定子目录内的子目录
【发布时间】:2015-07-05 19:14:43
【问题描述】:

我想匹配给定子文件夹中的所有子文件夹。

假设我有以下目录:

test/rock/martin
test/rock/steven
test/rock/steven/coolmusik
test/rock/steven/coolmusik/newmusic

test/pop/martin
test/pop/steven
test/pop/steven/mysubdir
test/pop/steven/anothersubdir

现在我想匹配 'rock' 和 'pop' 中的所有内容,但有给定名称的限制。在这种情况下,它是“史蒂文”。

到目前为止,以下minimatch glob-rule 工作正常:

minimatch('./test', ['!*(rock|pop|steven)'], {matchBase: true}))

上述规则的翻译:

隐藏所有不在摇滚、流行和史蒂文中的东西。


但是问题来了: 可以想象 minimatch 在这种特殊情况下不包括子目录。

我希望它像...

minimatch('./test', ['!*(rock|pop|steven|PLUS_SUBDIRS_OF_STEVEN)'], {matchBase: true}))

...但遗憾的是它不符合我的规则:

minimatch('./test', ['!*(rock|pop|steven/**)'], {matchBase: true}))

我的问题是: 除了rock+pop+steven+steven的子目录之外,我怎样才能隐藏所有的东西?


更好地了解目录结构:

test
|-rock
|--martin
|--steven
|---coolmusik
|----newmusic
|-pop
|--martin
|--steven
|---mysubdir
|---anothersubdir

另外:如果 minimatch 无法处理这个问题,上面规则的常规正则表达式会是什么样子?

【问题讨论】:

  • 你试过minimatch('./test/**' 吗?它是你的noglobstar 未标记?
  • 是的,但是没有用。它不会与路径匹配。

标签: javascript regex node.js regex-negation minimatch


【解决方案1】:

您无法通过列出每个文件然后对每个文件进行全局匹配来获得 .gitignore 样式的行为。对于初学者来说,这是非常昂贵的(你可能有一个 .gitignore'd 文件夹,其中包含 100000 个文件或其他东西),而且,你必须跟踪父级是否被忽略。但是,它变得更加复杂,因为如果某个规则没有被否定规则忽略,则规则可能会导致您必须查找特定项目。

来源:https://github.com/isaacs/minimatch/issues/8#issuecomment-5516685

'minimatch' 的所有者编写了一个名为 fstream-ignore 的模块来解决这个问题。 然而。这绝对超出了范围,与我的问题无关。如原始帖子中所述,我最终得到了一个常规的 Javascript 正则表达式。


正则表达式:

new RegExp(^test\/(rock|pop)(?:\/|$)(?:steven|$)(?:\/.*|$)$);

示例:

var re = /^test\/(rock|pop)(?:\/|$)(?:steven|$)(?:\/.*|$)/mg;
var paths = 'test/rock/martin\ntest/rock/steven\ntest/rock/steven/coolmusik\ntest/rock/steven/coolmusik/newmusic\ntest/pop/martin\ntest/pop/steven\ntest/pop/steven/mysubdir\ntest/pop/steven/anothersubdir';

var match;

while ((match = re.exec(paths)) !== null) {
  if (match.index === re.lastIndex) {
    re.lastIndex++;
  }
  var old_content = document.getElementById('results').innerHTML;
  document.getElementById('results').innerHTML = old_content + '<br>' + match[0];
}
<b>Verify against:</b>
<pre>
test/rock/martin
test/rock/steven
test/rock/steven/coolmusik
test/rock/steven/coolmusik/newmusic

test/pop/martin
test/pop/steven
test/pop/steven/mysubdir
test/pop/steven/anothersubdir
</pre>

<br><hr><br>

<b>Get <u>steven</u>'s results</b>:
<div id="results"></div>

【讨论】:

    猜你喜欢
    • 2015-05-08
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多