0

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

假设我有以下目录:

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

现在我想匹配“摇滚”和“流行”中的所有内容,并限制给定名称。在这种情况下,它是“史蒂文”。

到目前为止,以下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 无法处理这个问题,上面规则的常规正则表达式会是什么样子?

4

1 回答 1

0

您无法通过列出每个文件然后对每个文件进行全局匹配来获得 .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-07-06T18:14:02.620 回答