glob 笔记

node-glob 中对 glob 的规则有如下描述:

  • * Matches 0 or more characters in a single path portion

  • ? Matches 1 character

  • [...] Matches a range of characters, similar to a RegExp range.If the first character of the range is ! or ^ then it matchesany character not in the range.

  • !(pattern|pattern|pattern) Matches anything that does not match any of the patterns provided.

  • ?(pattern|pattern|pattern) Matches zero or one occurrence of the patterns provided.

  • +(pattern|pattern|pattern) Matches one or more occurrences of the patterns provided.

  • *(a|b|c) Matches zero or more occurrences of the patterns provided

  • @(pattern|pat*|pat?erN) Matches exactly one of the patterns provided

  • ** If a “globstar” is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches.It does not crawl symlinked directories.

名词

symlinked directories

软链接目录。例如,window 下创建的快捷方式

a single path portion

某级目录名或某个文件名

例如: /a/b/c.txt

[
    'a',
    'b',
    'c.txt'
]

a path portion

N 级目录或 N级目录+某文件

例如: /a/b/c.txt

[
    'a',
    'a/b',
    'a/b/c.txt',
    'b',
    'b/c.txt',
    'c.txt'
]

理解 .

If a file or directory path portion has a . as the first character, then it will not match any glob pattern unless that pattern’s corresponding path part also has a . as its first character.

For example, the pattern a/.*/c would match the file at a/.b/c. However the pattern a/*/c would not, because * does not start with a dot character.

目录名或者文件名如果以 . 开头,只有模式中对应部分以 . 开头才能匹配

当然,使用 node-glob 还可以这么干

const glob = require('glob')

glob('*', { dot: true })

理解 *

匹配 0 个或多个除 / 之外的字符,并且符合上面描述的使用 . 的规则

理解 **

如果 globstar 是 a path portion,那么它将匹配 N 级目录或 N级目录+某文件

原文并没有解释其它情况,只能自己手动测试,以下面目录结构为例

|-- .git
|-- readme.md
|-- aa
  |-- aa.md
  |-- bb
    |-- bb.md

**.git 之外的所有文件和文件夹路径
**/* 同上
**.md 只匹配 readme.md 的路径
*.md 同上
aa**.md 匹配为空
aa/**.md 匹配 aa.md 路径
**bb/**.md 匹配为空
**/bb**.md 匹配为空
**/bb/**.md 匹配 bb.md 路径

初步得出结论:

  • a path portion 即 ** 与其它模式内容之间必须被 / 分开,或者没有其它模式内容,只有 **

  • 如果不是一个 a path portion,就当作 * 看待

    原文作者:siwuxie
    原文地址: https://segmentfault.com/a/1190000010577468
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞