Blazing fast and accurate glob matcher written in JavaScript.
No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.
- Lightweight - No dependencies
- Minimal - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function.
- Fast - Loads in about 2ms (that's several times faster than a single frame of a HD movie at 60fps)
- Performant - Use the returned matcher function to speed up repeat matching (like when watching files)
- Accurate matching - Using wildcards (
*and?), globstars (**) for nested directories, advanced globbing with extglobs, braces, and POSIX brackets, and support for escaping special characters with\or quotes. - Well tested - Thousands of unit tests
See the library comparison to other libraries.
Click to expand
Install with npm:
npm install --save picomatchThe main export is a function that takes a glob pattern and an options object and returns a function for matching strings.
const pm = require('{%= name %}');
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{%= apidocs("./lib/picomatch.js") %}
The following options may be used with the main picomatch() function or any of the methods on the picomatch API.
In addition to the main picomatch options, the following options may also be used with the .scan method.
| Option | Type | Default value | Description |
|---|---|---|---|
tokens |
boolean |
false |
When true, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern |
parts |
boolean |
false |
When true, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when options.tokens is true |
Example
const picomatch = require('picomatch');
const result = picomatch.scan('!./foo/*.js', { tokens: true });
console.log(result);
// {
// prefix: '!./',
// input: '!./foo/*.js',
// start: 3,
// base: 'foo',
// glob: '*.js',
// isBrace: false,
// isBracket: false,
// isGlob: true,
// isExtglob: false,
// isGlobstar: false,
// negated: true,
// maxDepth: 2,
// tokens: [
// { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true },
// { value: 'foo', depth: 1, isGlob: false },
// { value: '*.js', depth: 1, isGlob: true }
// ],
// slashes: [ 2, 6 ],
// parts: [ 'foo', '*.js' ]
// }Type: function
Default: undefined
Custom function for expanding ranges in brace patterns. The [fill-range][] library is ideal for this purpose, or you can use custom code to do whatever you need.
Example
The following example shows how to create a glob that matches a folder
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')) // falseType: function
Default: undefined
Custom function for formatting strings before they're matched.
Example
// strip leading './' from strings
const format = str => str.replace(/^\.\//, '');
const isMatch = picomatch('foo/*.js', { format });
console.log(isMatch('./foo/bar.js')); //=> trueconst 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');- Basic globbing (Wildcard matching)
- Advanced globbing (extglobs, posix brackets, brace matching)
| Character | Description |
|---|---|
* |
Matches any character zero or more times, excluding path separators. Does not match path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the dot option to true. |
** |
Matches any character zero or more times, including path separators. Note that ** will only match path separators (/, and \\ with the windows option) when they are the only characters in a path segment. Thus, foo**/bar is equivalent to foo*/bar, and foo/a**b/bar is equivalent to foo/a*b/bar, and more than two consecutive stars in a glob path segment are regarded as a single star. Thus, foo/***/bar is equivalent to foo/*/bar. |
? |
Matches any character excluding path separators one time. Does not match path separators or leading dots. |
[abc] |
Matches any characters inside the brackets. For example, [abc] would match the characters a, b or c, and nothing else. |
Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions:
- Bash will match
foo/bar/bazwith*. Picomatch only matches nested directories with**. - Bash greedily matches with negated extglobs. For example, Bash 4.3 says that
!(foo)*should matchfooandfoobar, since the trailing*bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would returnfalsefor bothfooandfoobar.
| Pattern | Description |
|---|---|
@(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 |
Examples
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
console.log(pm.isMatch('azzz', '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
// risky quantified extglobs are treated literally by default
console.log(pm.makeRe('+(a|aa)'));
//=> /^(?:\+\(a\|aa\))$/
// increase the limit to allow a small amount of nested quantified extglobs
console.log(pm.isMatch('aaa', '+(+(a))', { maxExtglobRecursion: 1 })); // truePOSIX classes are disabled by default. Enable this feature by setting the posix option to true.
Enable POSIX bracket support
console.log(pm.makeRe('[[:word:]]+', { posix: true }));
//=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/Supported POSIX classes
The following named POSIX bracket expressions are supported:
[:alnum:]- Alphanumeric characters, equ[a-zA-Z0-9][:alpha:]- Alphabetical characters, equivalent to[a-zA-Z].[:ascii:]- ASCII characters, equivalent to[\\x00-\\x7F].[:blank:]- Space and tab characters, equivalent to[ \\t].[:cntrl:]- Control characters, equivalent to[\\x00-\\x1F\\x7F].[:digit:]- Numerical digits, equivalent to[0-9].[:graph:]- Graph characters, equivalent to[\\x21-\\x7E].[:lower:]- Lowercase letters, equivalent to[a-z].[:print:]- Print characters, equivalent to[\\x20-\\x7E ].[:punct:]- Punctuation and symbols, equivalent to[\\-!"#$%&\'()\\*+,./:;<=>?@[\\\\\\]^_`{|}~].[:space:]- Extended space characters, equivalent to[ \\t\\r\\n\\v\\f].[:upper:]- Uppercase letters, equivalent to[A-Z].[:word:]- Word characters (letters, numbers and underscores), equivalent to[A-Za-z0-9_].[:xdigit:]- Hexadecimal digits, equivalent to[A-Fa-f0-9].
See the Bash Reference Manual for more information.
Picomatch only does brace expansion of comma-delimited lists (e.g. a/{b,c}/d). For advanced matching with braces, use [micromatch][], which supports advanced syntax such as ranges (e.g. {01..03}) and increments (e.g. {2..10..2}).
If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes:
Special Characters
Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms.
To match any of the following characters as literals: $^*+?()[]{}| or a leading !, you must escape the character with a backslash, or wrap a sequence of characters in quotes.
Examples:
console.log(pm.makeRe('foo/bar \\(1\\)'));
console.log(pm.makeRe('foo/bar \\(1\\)'));The following table shows which features are supported by [minimatch][], [micromatch][], [picomatch][], [nanomatch][], [extglob][], [braces][], and [expand-brackets][].
Performance comparison of picomatch and minimatch.
# .makeRe star (*)
picomatch x 3,251,247 ops/sec ±0.25% (95 runs sampled)
minimatch x 497,224 ops/sec ±0.11% (100 runs sampled)
# .makeRe star; dot=true (*)
picomatch x 2,624,035 ops/sec ±0.16% (98 runs sampled)
minimatch x 446,244 ops/sec ±0.63% (99 runs sampled)
# .makeRe globstar (**)
picomatch x 2,524,465 ops/sec ±0.13% (99 runs sampled)
minimatch x 1,396,257 ops/sec ±0.58% (96 runs sampled)
# .makeRe globstars (**/**/**)
picomatch x 2,545,674 ops/sec ±0.10% (99 runs sampled)
minimatch x 1,196,835 ops/sec ±0.63% (98 runs sampled)
# .makeRe with leading star (*.txt)
picomatch x 2,537,708 ops/sec ±0.11% (100 runs sampled)
minimatch x 345,284 ops/sec ±0.64% (96 runs sampled)
# .makeRe - basic braces ({a,b,c}*.txt)
picomatch x 505,430 ops/sec ±1.04% (94 runs sampled)
minimatch x 107,991 ops/sec ±0.54% (99 runs sampled)
# .makeRe - short ranges ({a..z}*.txt)
picomatch x 371,179 ops/sec ±2.91% (77 runs sampled)
minimatch x 14,104 ops/sec ±0.61% (99 runs sampled)
# .makeRe - medium ranges ({1..100000}*.txt)
picomatch x 384,958 ops/sec ±1.70% (82 runs sampled)
minimatch x 2.55 ops/sec ±3.22% (11 runs sampled)
# .makeRe - long ranges ({1..10000000}*.txt)
picomatch x 382,552 ops/sec ±1.52% (71 runs sampled)
minimatch x 0.83 ops/sec ±5.67% (7 runs sampled))
The goal of this library is to be blazing fast, without compromising on accuracy.
Accuracy
The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: !(**/{a,b,*/c}).
Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements.
Performance
Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer.
Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Please read the contributing guide for advice on opening issues, pull requests, and coding standards.
Running Tests
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
npm install && npm testBuilding docs
(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)
To generate the readme, run the following command:
npm install -g verbose/verb#dev verb-generate-readme && verbJon Schlinkert
Copyright © 2017-present, Jon Schlinkert. Released under the MIT License.
