javascript - 如何编写一个匹配所有不在目录中的 js 文件的最小匹配 glob

标签 javascript node.js glob minimatch

我遇到这样一种情况,我需要一个单一的 glob 模式(使用 minimatch )来匹配不在特定目录中的所有 JavaScript 文件。不幸的是,我正在使用另一个不公开任何选项的工具(如 ignore glob),因此它必须是一个 glob 才能完成这项工作。

Here's what I have so far

screenshot of globtester

示例输入(它应该匹配顶部,但它应该匹配底部):

docs/foo/thing.js
docs/thing.js
client/docs/foo/thing.js
client/docs/thing.js

src/foo/thing.js
src/thing.js
docs-src/foo/thing.js
docs-src/thing.js
client/docs-src/foo/thing.js
client/docs-src/thing.js

到目前为止,这是我对 glob 模式的了解:

**/!(docs)/*.js

我正在匹配 docs/foo/thing.jsclient/docs/foo/thing.js 而不是匹配 docs-src/thing.jsclient/docs-src/thing.js。如果我将我的 glob 切换到 **/!(docs)/**/*.js 那么我可以匹配 client/docs-src/thing.js,但是我也匹配client/docs/thing.js

我不确定这是否可行,所以我可能需要为我的问题找到另一种解决方案:-/

最佳答案

我认为您可能遇到了 minimatch(或 fnmatch(3) 的任何实现)和 globstar 的限制。可能值得注意的是,据我所知,fnmatch 的 C 实现实际上确实实现了 globstar,但由于 fnmatch impl(包括 minimatch)服务于他们的 globbers 的利益,这可能会有所不同。

当用作 glob 时,您认为应该起作用的 glob 实际上确实起作用。

$ find . -type f
./docs/foo/thing.js
./docs/thing.js
./docs/nope.txt
./docs-src/foo/thing.js
./docs-src/thing.js
./x.sh
./client/docs/foo/thing.js
./client/docs/thing.js
./client/docs/nope.txt
./client/docs-src/foo/thing.js
./client/docs-src/thing.js
./client/docs-src/nope.txt
./client/nope.txt
./src/foo/thing.js
./src/thing.js

$ for i in ./!(docs)/**/*.js; do echo $i; done
./client/docs-src/foo/thing.js
./client/docs-src/thing.js
./client/docs/foo/thing.js
./client/docs/thing.js
./docs-src/foo/thing.js
./docs-src/thing.js
./src/foo/thing.js
./src/thing.js

$ node -p 'require("glob").sync("./!(docs)/**/*.js")'
[ './client/docs-src/foo/thing.js',
  './client/docs-src/thing.js',
  './client/docs/foo/thing.js',
  './client/docs/thing.js',
  './docs-src/foo/thing.js',
  './docs-src/thing.js',
  './src/foo/thing.js',
  './src/thing.js' ]

编辑:哦,我明白了,你只想匹配任何文件夹深度没有any docs 路径部分anywhere 的东西在路径中。不,这是不可能以支持任意深度的方式做到的,如 glob 或最小匹配模式。您必须使用排除,或构造一个看起来像这样的 glob:{!(docs),!(docs)/!(docs),!(docs)/!(docs)/!(docs) !(文档)/!(文档)/!(文档)/!(文档)}/*.js

否则,像 x/docs/y/z.js 这样的路径将匹配 **/!(docs)/**/*.js第一个 ** 不匹配,!(docs) 匹配 x,下一个 ** 匹配针对 docs/y 然后 *.jsz.js 匹配。

关于javascript - 如何编写一个匹配所有不在目录中的 js 文件的最小匹配 glob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48349959/

相关文章:

regex - glob 样式模式和正则表达式之间有什么区别?

azure - 存储 blob 删除批量删除除两个具有相似名称的目录之外的所有 blob

regex - 通配符和正则表达式

Javascript 循环遍历 JSON 对象数组找到实例,但将它们记录为未定义

node.js - 如何使用 Node.js postgres 测试 CRUD 操作

node.js - 个性洞察输入var nodejs

javascript - 与 puppeteer 师一起刮 table

javascript - 如果表单有效或无效,Bootstrap 表单会得到 true 或 false 然后 ajax

javascript - 更改 UIWebVIew 中 HTML 元素的位置

javascript - 不明白谷歌要求分析(一行是错误的)