picomatch

repository·master·Indexed 23 days ago

https://github.com/micromatch/picomatch

A high-performance, lightweight JavaScript glob matcher with no dependencies. It supports standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions. Version 4.0.5 provides a suite of API methods for parsing, scanning, and compiling glob patterns into regular expressions, as well as a dependency-free POSIX version for non-Node.js environments.

Tokens
4.6K
Snippets
17
Records
25
Agent score
29%

What's inside picomatch

  1. Advanced globbing with Extglobs

    master

    Extglobs allow for more complex pattern matching based on occurrences of a pattern:

    PatternDescription
    @(pattern)Match only one consecutive occurrence of pattern
    *(pattern)Match zero or more consecutive occurrences of pattern
    +(pattern)Match one or more consecutive occurrences of pattern
    ?(pattern)Match zero or one consecutive occurrences of pattern
    !(pattern)Match anything but pattern

    By default, risky quantified extglobs are treated literally. You can increase the nesting limit using the maxExtglobRecursion option.

    const pm = require('picomatch');
    
    // *(pattern) matches ZERO or more of "pattern"
    console.log(pm.isMatch('a', 'a*(z)')); // true
    console.log(pm.isMatch('az', 'a*(z)')); // true
    console.log(pm.isMatch('azzz', 'a*(z)')); // true
    
    // +(pattern) matches ONE or more of "pattern"
    console.log(pm.isMatch('a', 'a+(z)')); // false
    console.log(pm.isMatch('az', 'a+(z)')); // true
    
    // supports multiple extglobs
    console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false
    
    // supports nested extglobs
    console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true
    
    // increase the limit to allow a small amount of nested quantified extglobs
    console.log(pm.isMatch('aaa', '+(+(a))', { maxExtglobRecursion: 1 })); // true
  2. Compare Picomatch with other globbing libraries

    master

    Picomatch is a high-performance, accurate globbing library. Use the following comparison to decide if it fits your needs:

    Featureminimatchmicromatchpicomatchnanomatchextglobbracesexpand-brackets
    Wildcard matching (*?+)---
    Advancing globbing----
    Brace matching---
    Brace expansion----
    Extglobspartial---
    Posix brackets----
    Regular expression syntax--
    File system operations-------

    Key distinction: Picomatch supports brace matching (e.g., a/{b,c}/d) but does not support brace expansion (e.g., {01..03}). For expansion, use braces or micromatch.

  3. Basic globbing patterns in Picomatch

    master

    Picomatch supports standard wildcard matching patterns:

    • *: Matches any character zero or more times, excluding path separators. To match hidden files (dotfiles) or path separators, set the dot option to true.
    • **: Matches any character zero or more times, including path separators. Note that ** only matches path separators when they are the only characters in a path segment (e.g., foo**/bar is equivalent to foo*/bar). Consecutive stars beyond two (e.g., ***) are treated as a single star.
    • ?: Matches any single character excluding path separators or leading dots.
    • [abc]: Matches any one character contained within the brackets.

    Note on Bash compatibility: Unlike Bash, Picomatch requires ** to match nested directories; a single * will not match nested paths.

  4. Match special characters as literals

    master

    If your filepath contains special characters that are also used for glob or regular expression matching, you must escape them with backslashes or quotes to treat them as literals.

    Characters requiring escaping: $^*+?()[]

  5. Configure Picomatch options

    master

    The picomatch() function and its associated API methods accept an options object to customize matching behavior. Common configuration tasks include:

    • Case Sensitivity: Use nocase: true for case-insensitive matching (overridden by flags).
    • Dotfiles: Enable matching of dotfiles by setting dot: true.
    • Path Handling: Use basename: true (or matchBase: true) to match patterns without slashes against the basename of a path. Use windows: true to accept backslashes as path separators.
    • Glob Features: Enable/disable specific features like noglobstar (disables **), noextglob (disables +(a|b)), nobrace (disables {a,b}), or nonegate (disables ! negation).
    • Strictness: Use strictBrackets: true to throw errors on imbalanced brackets, braces, or parens.
    • Performance: fastpaths is enabled by default (true) to skip full parsing for common patterns.
  6. Use options.format to transform input strings

    master

    The format option accepts a function used to format strings before they are matched. This is useful for normalizing paths, such as stripping leading ./ or converting Windows paths to POSIX paths.

    // strip leading './' from strings
    const format = str => str.replace(/^\.\//, '');
    const isMatch = picomatch('foo/*.js', { format });
    console.log(isMatch('./foo/bar.js')); //=> true
  7. Use onMatch, onIgnore, and onResult callbacks

    master

    Picomatch provides lifecycle hooks via options to perform actions when items are processed:

    • onMatch: Called when an item matches the pattern.
    • onIgnore: Called when an item is excluded by an ignore pattern.
    • onResult: Called for every item, regardless of whether it matched or was ignored.

    Each callback receives an object containing { glob, regex, input, output }.

    const onMatch = ({ glob, regex, input, output }) => {
      console.log({ glob, regex, input, output });
    };
    
    const isMatch = picomatch('*', { onMatch });
    isMatch('foo');
    isMatch('bar');
    isMatch('baz');
    const onIgnore = ({ glob, regex, input, output }) => {
      console.log({ glob, regex, input, output });
    };
    
    const isMatch = picomatch('*', { onIgnore, ignore: 'f*' });
    isMatch('foo');
    isMatch('bar');
    isMatch('baz');
    const onResult = ({ glob, regex, input, output }) => {
      console.log({ glob, regex, input, output });
    };
    
    const isMatch = picomatch('*', { onResult, ignore: 'f*' });
    isMatch('foo');
    isMatch('bar');
    isMatch('baz');
  8. Basic usage of picomatch

    master

    The main export of picomatch is a function that takes a glob pattern (or an array of patterns) and an optional options object. It returns a matcher function. This returned function can be reused to perform multiple matches efficiently.

    const pm = require('picomatch');
    const isMatch = pm('*.js');
    
    console.log(isMatch('abcd')); //=> false
    console.log(isMatch('a.js')); //=> true
    console.log(isMatch('a.md')); //=> false
    console.log(isMatch('a/b.js')); //=> false
  9. Use options.expandRange to customize brace patterns

    master

    The expandRange option allows you to provide a custom function for expanding ranges in brace patterns (e.g., {a..z}). The function receives the range values as two arguments and must return a string to be used in the generated regex. It is recommended to wrap returned strings in parentheses.

    This is useful when integrating with libraries like fill-range to handle complex range expansions.

    const fill = require('fill-range');
    const regex = pm.makeRe('foo/{01..25}/bar', {
      expandRange(a, b) {
        return `(${fill(a, b, { toRegex: true })})`;
      }
    });
    
    console.log(regex);
    //=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/
    
    console.log(regex.test('foo/00/bar'))  // false
    console.log(regex.test('foo/01/bar'))  // true
    console.log(regex.test('foo/10/bar')) // true
    console.log(regex.test('foo/22/bar')) // true
    console.log(regex.test('foo/25/bar')) // true
    console.log(regex.test('foo/26/bar')) // false
  10. Parse a glob pattern with picomatch.parse()

    master

    The picomatch.parse(pattern, [options]) method parses a glob pattern to create the source string for a regular expression.

    const picomatch = require('picomatch');
    const result = picomatch.parse(pattern[, options]);
  11. Scan a glob pattern with picomatch.scan()

    master
    The picomatch.scan(input, [options]) method scans a glob pattern to separate it into segments, returning an object containing metadata about the pattern (e.g., prefix, base, glob, negation status).