Search code examples
javascriptnode.jsglob

Is there any difference between these 2 glob patterns?


images/**/*.{png,svg}
images/**/*.+(png|svg)

When I test them they usually produce the same result. But just need to make sure they are exactly the same.


Solution

  • They are not exactly the same and they will both potentially yield different results - refer to the glob primer for further info. It states:

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

    Your second pattern; images/**/*.+(png|svg), will match one or more occurrences of either png or svg at the end of a filename.

    However, your first pattern; images/**/*.{png,svg}, will match only when there is one occurrence of either png or svg at the end of a filename.

    Example:

    Let's say we have four files named:

    • foo.svg
    • foo.svgsvg
    • foo.png
    • foo.pngpngpng

    and their paths are:

    .
    ├── images
    │   ├── ...
    │   └── quux
    │       ├── foo.svg
    │       ├── foo.svgsvg
    │       ├── foo.png
    │       └── foo.pngpngpng
    

    Matched Results

    Given your two example patterns - your first pattern; images/**/*.{png,svg}, will match the following two paths only:

    • images/quux/foo.svg
    • images/quux/foo.png

    Note: the paths to files foo.svgsvg and foo.pngpngpng have been ignored

    However your second pattern; images/**/*.+(png|svg) will match all four file paths, namely:

    • images/quux/foo.svg
    • images/quux/foo.svgsvg
    • images/quux/foo.png
    • images/quux/foo.pngpngpng

    "When I test them they usually produce the same result."

    This is because it's unlikely that you've ever had a file with an extension such as .pngpng or .svgsvgsvg (i.e. when it has more than one occurrence of png or svg at the end). Nor is it likely that you ever will.

    However, I recommend that you utilize the first glob pattern, i.e. images/**/*.{png,svg}, as it's more concise to what you're actually wanting to match.