1# micromatch [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/micromatch.svg?style=flat)](https://www.npmjs.com/package/micromatch) [![NPM monthly downloads](https://img.shields.io/npm/dm/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![NPM total downloads](https://img.shields.io/npm/dt/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![Linux Build Status](https://img.shields.io/travis/micromatch/micromatch.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/micromatch)
2
3> Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch.
4
5Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
6
7## Table of Contents
8
9<details>
10<summary><strong>Details</strong></summary>
11
12- [Install](#install)
13- [Quickstart](#quickstart)
14- [Why use micromatch?](#why-use-micromatch)
15  * [Matching features](#matching-features)
16- [Switching to micromatch](#switching-to-micromatch)
17  * [From minimatch](#from-minimatch)
18  * [From multimatch](#from-multimatch)
19- [API](#api)
20- [Options](#options)
21- [Options Examples](#options-examples)
22  * [options.basename](#optionsbasename)
23  * [options.bash](#optionsbash)
24  * [options.expandRange](#optionsexpandrange)
25  * [options.format](#optionsformat)
26  * [options.ignore](#optionsignore)
27  * [options.matchBase](#optionsmatchbase)
28  * [options.noextglob](#optionsnoextglob)
29  * [options.nonegate](#optionsnonegate)
30  * [options.noglobstar](#optionsnoglobstar)
31  * [options.nonull](#optionsnonull)
32  * [options.nullglob](#optionsnullglob)
33  * [options.onIgnore](#optionsonignore)
34  * [options.onMatch](#optionsonmatch)
35  * [options.onResult](#optionsonresult)
36  * [options.posixSlashes](#optionsposixslashes)
37  * [options.unescape](#optionsunescape)
38- [Extended globbing](#extended-globbing)
39  * [Extglobs](#extglobs)
40  * [Braces](#braces)
41  * [Regex character classes](#regex-character-classes)
42  * [Regex groups](#regex-groups)
43  * [POSIX bracket expressions](#posix-bracket-expressions)
44- [Notes](#notes)
45  * [Bash 4.3 parity](#bash-43-parity)
46  * [Backslashes](#backslashes)
47- [Benchmarks](#benchmarks)
48  * [Running benchmarks](#running-benchmarks)
49  * [Latest results](#latest-results)
50- [Contributing](#contributing)
51- [About](#about)
52
53</details>
54
55## Install
56
57Install with [npm](https://www.npmjs.com/):
58
59```sh
60$ npm install --save micromatch
61```
62
63## Quickstart
64
65```js
66const micromatch = require('micromatch');
67// micromatch(list, patterns[, options]);
68```
69
70The [main export](#micromatch) takes a list of strings and one or more glob patterns:
71
72```js
73console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['f*', 'b*'])) //=> ['foo', 'bar', 'baz']
74console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['*', '!b*'])) //=> ['foo', 'qux']
75```
76
77Use [.isMatch()](#ismatch) to for boolean matching:
78
79```js
80console.log(micromatch.isMatch('foo', 'f*')) //=> true
81console.log(micromatch.isMatch('foo', ['b*', 'f*'])) //=> true
82```
83
84[Switching](#switching-to-micromatch) from minimatch and multimatch is easy!
85
86<br>
87
88## Why use micromatch?
89
90> micromatch is a [replacement](#switching-to-micromatch) for minimatch and multimatch
91
92* Supports all of the same matching features as [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch)
93* More complete support for the Bash 4.3 specification than minimatch and multimatch. Micromatch passes _all of the spec tests_ from bash, including some that bash still fails.
94* **Fast & Performant** - Loads in about 5ms and performs [fast matches](#benchmarks).
95* **Glob matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories
96* **[Advanced globbing](#advanced-globbing)** - Supports [extglobs](#extglobs), [braces](#braces), and [POSIX brackets](#posix-bracket-expressions), and support for escaping special characters with `\` or quotes.
97* **Accurate** - Covers more scenarios [than minimatch](https://github.com/yarnpkg/yarn/pull/3339)
98* **Well tested** - More than 5,000 [test assertions](./test)
99* **Windows support** - More reliable windows support than minimatch and multimatch.
100* **[Safe](https://github.com/micromatch/braces#braces-is-safe)** - Micromatch is not subject to DoS with brace patterns like minimatch and multimatch.
101
102### Matching features
103
104* Support for multiple glob patterns (no need for wrappers like multimatch)
105* Wildcards (`**`, `*.js`)
106* Negation (`'!a/*.js'`, `'*!(b).js']`)
107* [extglobs](#extglobs) (`+(x|y)`, `!(a|b)`)
108* [POSIX character classes](#posix-bracket-expressions) (`[[:alpha:][:digit:]]`)
109* [brace expansion](https://github.com/micromatch/braces) (`foo/{1..5}.md`, `bar/{a,b,c}.js`)
110* regex character classes (`foo-[1-5].js`)
111* regex logical "or" (`foo/(abc|xyz).js`)
112
113You can mix and match these features to create whatever patterns you need!
114
115## Switching to micromatch
116
117_(There is one notable difference between micromatch and minimatch in regards to how backslashes are handled. See [the notes about backslashes](#backslashes) for more information.)_
118
119### From minimatch
120
121Use [micromatch.isMatch()](#ismatch) instead of `minimatch()`:
122
123```js
124console.log(micromatch.isMatch('foo', 'b*')); //=> false
125```
126
127Use [micromatch.match()](#match) instead of `minimatch.match()`:
128
129```js
130console.log(micromatch.match(['foo', 'bar'], 'b*')); //=> 'bar'
131```
132
133### From multimatch
134
135Same signature:
136
137```js
138console.log(micromatch(['foo', 'bar', 'baz'], ['f*', '*z'])); //=> ['foo', 'baz']
139```
140
141## API
142
143**Params**
144
145* **{String|Array<string>}**: list List of strings to match.
146* **{String|Array<string>}**: patterns One or more glob patterns to use for matching.
147* **{Object}**: options See available [options](#options)
148* `returns` **{Array}**: Returns an array of matches
149
150**Example**
151
152```js
153const mm = require('micromatch');
154// mm(list, patterns[, options]);
155
156console.log(mm(['a.js', 'a.txt'], ['*.js']));
157//=> [ 'a.js' ]
158```
159
160### [.matcher](index.js#L98)
161
162Returns a matcher function from the given glob `pattern` and `options`. The returned function takes a string to match as its only argument and returns true if the string is a match.
163
164**Params**
165
166* `pattern` **{String}**: Glob pattern
167* `options` **{Object}**
168* `returns` **{Function}**: Returns a matcher function.
169
170**Example**
171
172```js
173const mm = require('micromatch');
174// mm.matcher(pattern[, options]);
175
176const isMatch = mm.matcher('*.!(*a)');
177console.log(isMatch('a.a')); //=> false
178console.log(isMatch('a.b')); //=> true
179```
180
181### [.isMatch](index.js#L117)
182
183Returns true if **any** of the given glob `patterns` match the specified `string`.
184
185**Params**
186
187* **{String}**: str The string to test.
188* **{String|Array}**: patterns One or more glob patterns to use for matching.
189* **{Object}**: See available [options](#options).
190* `returns` **{Boolean}**: Returns true if any patterns match `str`
191
192**Example**
193
194```js
195const mm = require('micromatch');
196// mm.isMatch(string, patterns[, options]);
197
198console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
199console.log(mm.isMatch('a.a', 'b.*')); //=> false
200```
201
202### [.not](index.js#L136)
203
204Returns a list of strings that _**do not match any**_ of the given `patterns`.
205
206**Params**
207
208* `list` **{Array}**: Array of strings to match.
209* `patterns` **{String|Array}**: One or more glob pattern to use for matching.
210* `options` **{Object}**: See available [options](#options) for changing how matches are performed
211* `returns` **{Array}**: Returns an array of strings that **do not match** the given patterns.
212
213**Example**
214
215```js
216const mm = require('micromatch');
217// mm.not(list, patterns[, options]);
218
219console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
220//=> ['b.b', 'c.c']
221```
222
223### [.contains](index.js#L176)
224
225Returns true if the given `string` contains the given pattern. Similar to [.isMatch](#isMatch) but the pattern can match any part of the string.
226
227**Params**
228
229* `str` **{String}**: The string to match.
230* `patterns` **{String|Array}**: Glob pattern to use for matching.
231* `options` **{Object}**: See available [options](#options) for changing how matches are performed
232* `returns` **{Boolean}**: Returns true if the patter matches any part of `str`.
233
234**Example**
235
236```js
237var mm = require('micromatch');
238// mm.contains(string, pattern[, options]);
239
240console.log(mm.contains('aa/bb/cc', '*b'));
241//=> true
242console.log(mm.contains('aa/bb/cc', '*d'));
243//=> false
244```
245
246### [.matchKeys](index.js#L218)
247
248Filter the keys of the given object with the given `glob` pattern and `options`. Does not attempt to match nested keys. If you need this feature, use [glob-object](https://github.com/jonschlinkert/glob-object) instead.
249
250**Params**
251
252* `object` **{Object}**: The object with keys to filter.
253* `patterns` **{String|Array}**: One or more glob patterns to use for matching.
254* `options` **{Object}**: See available [options](#options) for changing how matches are performed
255* `returns` **{Object}**: Returns an object with only keys that match the given patterns.
256
257**Example**
258
259```js
260const mm = require('micromatch');
261// mm.matchKeys(object, patterns[, options]);
262
263const obj = { aa: 'a', ab: 'b', ac: 'c' };
264console.log(mm.matchKeys(obj, '*b'));
265//=> { ab: 'b' }
266```
267
268### [.some](index.js#L247)
269
270Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
271
272**Params**
273
274* `list` **{String|Array}**: The string or array of strings to test. Returns as soon as the first match is found.
275* `patterns` **{String|Array}**: One or more glob patterns to use for matching.
276* `options` **{Object}**: See available [options](#options) for changing how matches are performed
277* `returns` **{Boolean}**: Returns true if any patterns match `str`
278
279**Example**
280
281```js
282const mm = require('micromatch');
283// mm.some(list, patterns[, options]);
284
285console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
286// true
287console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
288// false
289```
290
291### [.every](index.js#L283)
292
293Returns true if every string in the given `list` matches any of the given glob `patterns`.
294
295**Params**
296
297* `list` **{String|Array}**: The string or array of strings to test.
298* `patterns` **{String|Array}**: One or more glob patterns to use for matching.
299* `options` **{Object}**: See available [options](#options) for changing how matches are performed
300* `returns` **{Boolean}**: Returns true if any patterns match `str`
301
302**Example**
303
304```js
305const mm = require('micromatch');
306// mm.every(list, patterns[, options]);
307
308console.log(mm.every('foo.js', ['foo.js']));
309// true
310console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
311// true
312console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
313// false
314console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
315// false
316```
317
318### [.all](index.js#L322)
319
320Returns true if **all** of the given `patterns` match the specified string.
321
322**Params**
323
324* `str` **{String|Array}**: The string to test.
325* `patterns` **{String|Array}**: One or more glob patterns to use for matching.
326* `options` **{Object}**: See available [options](#options) for changing how matches are performed
327* `returns` **{Boolean}**: Returns true if any patterns match `str`
328
329**Example**
330
331```js
332const mm = require('micromatch');
333// mm.all(string, patterns[, options]);
334
335console.log(mm.all('foo.js', ['foo.js']));
336// true
337
338console.log(mm.all('foo.js', ['*.js', '!foo.js']));
339// false
340
341console.log(mm.all('foo.js', ['*.js', 'foo.js']));
342// true
343
344console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
345// true
346```
347
348### [.capture](index.js#L349)
349
350Returns an array of matches captured by `pattern` in `string, or`null` if the pattern did not match.
351
352**Params**
353
354* `glob` **{String}**: Glob pattern to use for matching.
355* `input` **{String}**: String to match
356* `options` **{Object}**: See available [options](#options) for changing how matches are performed
357* `returns` **{Boolean}**: Returns an array of captures if the input matches the glob pattern, otherwise `null`.
358
359**Example**
360
361```js
362const mm = require('micromatch');
363// mm.capture(pattern, string[, options]);
364
365console.log(mm.capture('test/*.js', 'test/foo.js'));
366//=> ['foo']
367console.log(mm.capture('test/*.js', 'foo/bar.css'));
368//=> null
369```
370
371### [.makeRe](index.js#L375)
372
373Create a regular expression from the given glob `pattern`.
374
375**Params**
376
377* `pattern` **{String}**: A glob pattern to convert to regex.
378* `options` **{Object}**
379* `returns` **{RegExp}**: Returns a regex created from the given pattern.
380
381**Example**
382
383```js
384const mm = require('micromatch');
385// mm.makeRe(pattern[, options]);
386
387console.log(mm.makeRe('*.js'));
388//=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
389```
390
391### [.scan](index.js#L391)
392
393Scan a glob pattern to separate the pattern into segments. Used by the [split](#split) method.
394
395**Params**
396
397* `pattern` **{String}**
398* `options` **{Object}**
399* `returns` **{Object}**: Returns an object with
400
401**Example**
402
403```js
404const mm = require('micromatch');
405const state = mm.scan(pattern[, options]);
406```
407
408### [.parse](index.js#L407)
409
410Parse a glob pattern to create the source string for a regular expression.
411
412**Params**
413
414* `glob` **{String}**
415* `options` **{Object}**
416* `returns` **{Object}**: Returns an object with useful properties and output to be used as regex source string.
417
418**Example**
419
420```js
421const mm = require('micromatch');
422const state = mm(pattern[, options]);
423```
424
425### [.braces](index.js#L434)
426
427Process the given brace `pattern`.
428
429**Params**
430
431* `pattern` **{String}**: String with brace pattern to process.
432* `options` **{Object}**: Any [options](#options) to change how expansion is performed. See the [braces](https://github.com/micromatch/braces) library for all available options.
433* `returns` **{Array}**
434
435**Example**
436
437```js
438const { braces } = require('micromatch');
439console.log(braces('foo/{a,b,c}/bar'));
440//=> [ 'foo/(a|b|c)/bar' ]
441
442console.log(braces('foo/{a,b,c}/bar', { expand: true }));
443//=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
444```
445
446## Options
447
448| **Option** | **Type** | **Default value** | **Description** |
449| --- | --- | --- | --- |
450| `basename`            | `boolean`      | `false`     | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes.  For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. |
451| `bash`                | `boolean`      | `false`     | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). |
452| `capture`             | `boolean`      | `undefined` | Return regex matches in supporting methods. |
453| `contains`            | `boolean`      | `undefined` | Allows glob to match any part of the given string(s). |
454| `cwd`                 | `string`       | `process.cwd()` | Current working directory. Used by `picomatch.split()` |
455| `debug`               | `boolean`      | `undefined` | Debug regular expressions when an error is thrown. |
456| `dot`                 | `boolean`      | `false`     | Match dotfiles. Otherwise dotfiles are ignored unless a `.` is explicitly defined in the pattern. |
457| `expandRange`         | `function`     | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. This option is overridden by the `expandBrace` option. |
458| `failglob`            | `boolean`      | `false`     | Similar to the `failglob` behavior in Bash, throws an error when no matches are found. Based on the bash option of the same name. |
459| `fastpaths`           | `boolean`      | `true`      | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. |
460| `flags`               | `boolean`      | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. |
461| [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. |
462| `ignore`              | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. |
463| `keepQuotes`          | `boolean`      | `false`     | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes.  |
464| `literalBrackets`     | `boolean`      | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. |
465| `lookbehinds`         | `boolean`      | `true`      | Support regex positive and negative lookbehinds. Note that you must be using Node 8.1.10 or higher to enable regex lookbehinds. |
466| `matchBase`           | `boolean`      | `false`     | Alias for `basename` |
467| `maxLength`           | `boolean`      | `65536`     | Limit the max length of the input string. An error is thrown if the input string is longer than this value. |
468| `nobrace`             | `boolean`      | `false`     | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. |
469| `nobracket`           | `boolean`      | `undefined` | Disable matching with regex brackets. |
470| `nocase`              | `boolean`      | `false`     | Perform case-insensitive matching. Equivalent to the regex `i` flag. Note that this option is ignored when the `flags` option is defined. |
471| `nodupes`             | `boolean`      | `true`      | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. |
472| `noext`               | `boolean`      | `false`     | Alias for `noextglob` |
473| `noextglob`           | `boolean`      | `false`     | Disable support for matching with [extglobs](#extglobs) (like `+(a\|b)`) |
474| `noglobstar`          | `boolean`      | `false`     | Disable support for matching nested directories with globstars (`**`) |
475| `nonegate`            | `boolean`      | `false`     | Disable support for negating with leading `!` |
476| `noquantifiers`       | `boolean`      | `false`     | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. |
477| [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. |
478| [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. |
479| [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. |
480| `posix`               | `boolean`      | `false`     | Support [POSIX character classes](#posix-bracket-expressions) ("posix brackets"). |
481| `posixSlashes`        | `boolean`      | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself |
482| `prepend`             | `boolean`      | `undefined` | String to prepend to the generated regex used for matching. |
483| `regex`               | `boolean`      | `false`     | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). |
484| `strictBrackets`      | `boolean`      | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. |
485| `strictSlashes`       | `boolean`      | `undefined` | When true, picomatch won't match trailing slashes with single stars. |
486| `unescape`            | `boolean`      | `undefined` | Remove preceding backslashes from escaped glob characters before creating the regular expression to perform matches. |
487| `unixify`             | `boolean`      | `undefined` | Alias for `posixSlashes`, for backwards compatitibility. |
488
489## Options Examples
490
491### options.basename
492
493Allow glob patterns without slashes to match a file path based on its basename. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `matchBase`.
494
495**Type**: `Boolean`
496
497**Default**: `false`
498
499**Example**
500
501```js
502micromatch(['a/b.js', 'a/c.md'], '*.js');
503//=> []
504
505micromatch(['a/b.js', 'a/c.md'], '*.js', { basename: true });
506//=> ['a/b.js']
507```
508
509### options.bash
510
511Enabled by default, this option enforces bash-like behavior with stars immediately following a bracket expression. Bash bracket expressions are similar to regex character classes, but unlike regex, a star following a bracket expression **does not repeat the bracketed characters**. Instead, the star is treated the same as any other star.
512
513**Type**: `Boolean`
514
515**Default**: `true`
516
517**Example**
518
519```js
520const files = ['abc', 'ajz'];
521console.log(micromatch(files, '[a-c]*'));
522//=> ['abc', 'ajz']
523
524console.log(micromatch(files, '[a-c]*', { bash: false }));
525```
526
527### options.expandRange
528
529**Type**: `function`
530
531**Default**: `undefined`
532
533Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need.
534
535**Example**
536
537The following example shows how to create a glob that matches a numeric folder name between `01` and `25`, with leading zeros.
538
539```js
540const fill = require('fill-range');
541const regex = micromatch.makeRe('foo/{01..25}/bar', {
542  expandRange(a, b) {
543    return `(${fill(a, b, { toRegex: true })})`;
544  }
545});
546
547console.log(regex)
548//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/
549
550console.log(regex.test('foo/00/bar')) // false
551console.log(regex.test('foo/01/bar')) // true
552console.log(regex.test('foo/10/bar')) // true
553console.log(regex.test('foo/22/bar')) // true
554console.log(regex.test('foo/25/bar')) // true
555console.log(regex.test('foo/26/bar')) // false
556```
557
558### options.format
559
560**Type**: `function`
561
562**Default**: `undefined`
563
564Custom function for formatting strings before they're matched.
565
566**Example**
567
568```js
569// strip leading './' from strings
570const format = str => str.replace(/^\.\//, '');
571const isMatch = picomatch('foo/*.js', { format });
572console.log(isMatch('./foo/bar.js')) //=> true
573```
574
575### options.ignore
576
577String or array of glob patterns to match files to ignore.
578
579**Type**: `String|Array`
580
581**Default**: `undefined`
582
583```js
584const isMatch = micromatch.matcher('*', { ignore: 'f*' });
585console.log(isMatch('foo')) //=> false
586console.log(isMatch('bar')) //=> true
587console.log(isMatch('baz')) //=> true
588```
589
590### options.matchBase
591
592Alias for [options.basename](#options-basename).
593
594### options.noextglob
595
596Disable extglob support, so that [extglobs](#extglobs) are regarded as literal characters.
597
598**Type**: `Boolean`
599
600**Default**: `undefined`
601
602**Examples**
603
604```js
605console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)'));
606//=> ['a/b', 'a/!(z)']
607
608console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', { noextglob: true }));
609//=> ['a/!(z)'] (matches only as literal characters)
610```
611
612### options.nonegate
613
614Disallow negation (`!`) patterns, and treat leading `!` as a literal character to match.
615
616**Type**: `Boolean`
617
618**Default**: `undefined`
619
620### options.noglobstar
621
622Disable matching with globstars (`**`).
623
624**Type**: `Boolean`
625
626**Default**: `undefined`
627
628```js
629micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**');
630//=> ['a/b', 'a/b/c', 'a/b/c/d']
631
632micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true});
633//=> ['a/b']
634```
635
636### options.nonull
637
638Alias for [options.nullglob](#options-nullglob).
639
640### options.nullglob
641
642If `true`, when no matches are found the actual (arrayified) glob pattern is returned instead of an empty array. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `nonull`.
643
644**Type**: `Boolean`
645
646**Default**: `undefined`
647
648### options.onIgnore
649
650```js
651const onIgnore = ({ glob, regex, input, output }) => {
652  console.log({ glob, regex, input, output });
653  // { glob: '*', regex: /^(?:(?!\.)(?=.)[^\/]*?\/?)$/, input: 'foo', output: 'foo' }
654};
655
656const isMatch = micromatch.matcher('*', { onIgnore, ignore: 'f*' });
657isMatch('foo');
658isMatch('bar');
659isMatch('baz');
660```
661
662### options.onMatch
663
664```js
665const onMatch = ({ glob, regex, input, output }) => {
666  console.log({ input, output });
667  // { input: 'some\\path', output: 'some/path' }
668  // { input: 'some\\path', output: 'some/path' }
669  // { input: 'some\\path', output: 'some/path' }
670};
671
672const isMatch = micromatch.matcher('**', { onMatch, posixSlashes: true });
673isMatch('some\\path');
674isMatch('some\\path');
675isMatch('some\\path');
676```
677
678### options.onResult
679
680```js
681const onResult = ({ glob, regex, input, output }) => {
682  console.log({ glob, regex, input, output });
683};
684
685const isMatch = micromatch('*', { onResult, ignore: 'f*' });
686isMatch('foo');
687isMatch('bar');
688isMatch('baz');
689```
690
691### options.posixSlashes
692
693Convert path separators on returned files to posix/unix-style forward slashes. Aliased as `unixify` for backwards compatibility.
694
695**Type**: `Boolean`
696
697**Default**: `true` on windows, `false` everywhere else.
698
699**Example**
700
701```js
702console.log(micromatch.match(['a\\b\\c'], 'a/**'));
703//=> ['a/b/c']
704
705console.log(micromatch.match(['a\\b\\c'], { posixSlashes: false }));
706//=> ['a\\b\\c']
707```
708
709### options.unescape
710
711Remove backslashes from escaped glob characters before creating the regular expression to perform matches.
712
713**Type**: `Boolean`
714
715**Default**: `undefined`
716
717**Example**
718
719In this example we want to match a literal `*`:
720
721```js
722console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c'));
723//=> ['a\\*c']
724
725console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c', { unescape: true }));
726//=> ['a*c']
727```
728
729<br>
730<br>
731
732## Extended globbing
733
734Micromatch supports the following extended globbing features.
735
736### Extglobs
737
738Extended globbing, as described by the bash man page:
739
740| **pattern** | **regex equivalent** | **description** |
741| --- | --- | --- |
742| `?(pattern)` | `(pattern)?` | Matches zero or one occurrence of the given patterns |
743| `*(pattern)` | `(pattern)*` | Matches zero or more occurrences of the given patterns |
744| `+(pattern)` | `(pattern)+` | Matches one or more occurrences of the given patterns |
745| `@(pattern)` | `(pattern)` <sup>*</sup> | Matches one of the given patterns |
746| `!(pattern)` | N/A (equivalent regex is much more complicated) | Matches anything except one of the given patterns |
747
748<sup><strong>*</strong></sup> Note that `@` isn't a regex character.
749
750### Braces
751
752Brace patterns can be used to match specific ranges or sets of characters.
753
754**Example**
755
756The pattern `{f,b}*/{1..3}/{b,q}*` would match any of following strings:
757
758```
759foo/1/bar
760foo/2/bar
761foo/3/bar
762baz/1/qux
763baz/2/qux
764baz/3/qux
765```
766
767Visit [braces](https://github.com/micromatch/braces) to see the full range of features and options related to brace expansion, or to create brace matching or expansion related issues.
768
769### Regex character classes
770
771Given the list: `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`:
772
773* `[ac].js`: matches both `a` and `c`, returning `['a.js', 'c.js']`
774* `[b-d].js`: matches from `b` to `d`, returning `['b.js', 'c.js', 'd.js']`
775* `[b-d].js`: matches from `b` to `d`, returning `['b.js', 'c.js', 'd.js']`
776* `a/[A-Z].js`: matches and uppercase letter, returning `['a/E.md']`
777
778Learn about [regex character classes](http://www.regular-expressions.info/charclass.html).
779
780### Regex groups
781
782Given `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`:
783
784* `(a|c).js`: would match either `a` or `c`, returning `['a.js', 'c.js']`
785* `(b|d).js`: would match either `b` or `d`, returning `['b.js', 'd.js']`
786* `(b|[A-Z]).js`: would match either `b` or an uppercase letter, returning `['b.js', 'E.js']`
787
788As with regex, parens can be nested, so patterns like `((a|b)|c)/b` will work. Although brace expansion might be friendlier to use, depending on preference.
789
790### POSIX bracket expressions
791
792POSIX brackets are intended to be more user-friendly than regex character classes. This of course is in the eye of the beholder.
793
794**Example**
795
796```js
797console.log(micromatch.isMatch('a1', '[[:alpha:][:digit:]]')) //=> true
798console.log(micromatch.isMatch('a1', '[[:alpha:][:alpha:]]')) //=> false
799```
800
801***
802
803## Notes
804
805### Bash 4.3 parity
806
807Whenever possible matching behavior is based on behavior Bash 4.3, which is mostly consistent with minimatch.
808
809However, it's suprising how many edge cases and rabbit holes there are with glob matching, and since there is no real glob specification, and micromatch is more accurate than both Bash and minimatch, there are cases where best-guesses were made for behavior. In a few cases where Bash had no answers, we used wildmatch (used by git) as a fallback.
810
811### Backslashes
812
813There is an important, notable difference between minimatch and micromatch _in regards to how backslashes are handled_ in glob patterns.
814
815* Micromatch exclusively and explicitly reserves backslashes for escaping characters in a glob pattern, even on windows, which is consistent with bash behavior. _More importantly, unescaping globs can result in unsafe regular expressions_.
816* Minimatch converts all backslashes to forward slashes, which means you can't use backslashes to escape any characters in your glob patterns.
817
818We made this decision for micromatch for a couple of reasons:
819
820* Consistency with bash conventions.
821* Glob patterns are not filepaths. They are a type of [regular language](https://en.wikipedia.org/wiki/Regular_language) that is converted to a JavaScript regular expression. Thus, when forward slashes are defined in a glob pattern, the resulting regular expression will match windows or POSIX path separators just fine.
822
823**A note about joining paths to globs**
824
825Note that when you pass something like `path.join('foo', '*')` to micromatch, you are creating a filepath and expecting it to still work as a glob pattern. This causes problems on windows, since the `path.sep` is `\\`.
826
827In other words, since `\\` is reserved as an escape character in globs, on windows `path.join('foo', '*')` would result in `foo\\*`, which tells micromatch to match `*` as a literal character. This is the same behavior as bash.
828
829To solve this, you might be inspired to do something like `'foo\\*'.replace(/\\/g, '/')`, but this causes another, potentially much more serious, problem.
830
831## Benchmarks
832
833### Running benchmarks
834
835Install dependencies for running benchmarks:
836
837```sh
838$ cd bench && npm install
839```
840
841Run the benchmarks:
842
843```sh
844$ npm run bench
845```
846
847### Latest results
848
849As of April 10, 2019 (longer bars are better):
850
851```sh
852# .makeRe star
853  micromatch x 1,724,735 ops/sec ±1.69% (87 runs sampled))
854  minimatch x 649,565 ops/sec ±1.93% (91 runs sampled)
855
856# .makeRe star; dot=true
857  micromatch x 1,302,127 ops/sec ±1.43% (92 runs sampled)
858  minimatch x 556,242 ops/sec ±0.71% (86 runs sampled)
859
860# .makeRe globstar
861  micromatch x 1,393,992 ops/sec ±0.71% (89 runs sampled)
862  minimatch x 1,112,801 ops/sec ±2.02% (91 runs sampled)
863
864# .makeRe globstars
865  micromatch x 1,419,097 ops/sec ±0.34% (94 runs sampled)
866  minimatch x 541,207 ops/sec ±1.66% (93 runs sampled)
867
868# .makeRe with leading star
869  micromatch x 1,247,825 ops/sec ±0.97% (94 runs sampled)
870  minimatch x 489,660 ops/sec ±0.63% (94 runs sampled)
871
872# .makeRe - braces
873  micromatch x 206,301 ops/sec ±1.62% (81 runs sampled))
874  minimatch x 115,986 ops/sec ±0.59% (94 runs sampled)
875
876# .makeRe braces - range (expanded)
877  micromatch x 27,782 ops/sec ±0.79% (88 runs sampled)
878  minimatch x 4,683 ops/sec ±1.20% (92 runs sampled)
879
880# .makeRe braces - range (compiled)
881  micromatch x 134,056 ops/sec ±2.73% (77 runs sampled))
882  minimatch x 977 ops/sec ±0.85% (91 runs sampled)d)
883
884# .makeRe braces - nested ranges (expanded)
885  micromatch x 18,353 ops/sec ±0.95% (91 runs sampled)
886  minimatch x 4,514 ops/sec ±1.04% (93 runs sampled)
887
888# .makeRe braces - nested ranges (compiled)
889  micromatch x 38,916 ops/sec ±1.85% (82 runs sampled)
890  minimatch x 980 ops/sec ±0.54% (93 runs sampled)d)
891
892# .makeRe braces - set (compiled)
893  micromatch x 141,088 ops/sec ±1.70% (70 runs sampled))
894  minimatch x 43,385 ops/sec ±0.87% (93 runs sampled)
895
896# .makeRe braces - nested sets (compiled)
897  micromatch x 87,272 ops/sec ±2.85% (71 runs sampled))
898  minimatch x 25,327 ops/sec ±1.59% (86 runs sampled)
899```
900
901## Contributing
902
903All contributions are welcome! Please read [the contributing guide](.github/contributing.md) to get started.
904
905**Bug reports**
906
907Please create an issue if you encounter a bug or matching behavior that doesn't seem correct. If you find a matching-related issue, please:
908
909* [research existing issues first](../../issues) (open and closed)
910* visit the [GNU Bash documentation](https://www.gnu.org/software/bash/manual/) to see how Bash deals with the pattern
911* visit the [minimatch](https://github.com/isaacs/minimatch) documentation to cross-check expected behavior in node.js
912* if all else fails, since there is no real specification for globs we will probably need to discuss expected behavior and decide how to resolve it. which means any detail you can provide to help with this discussion would be greatly appreciated.
913
914**Platform issues**
915
916It's important to us that micromatch work consistently on all platforms. If you encounter any platform-specific matching or path related issues, please let us know (pull requests are also greatly appreciated).
917
918## About
919
920<details>
921<summary><strong>Contributing</strong></summary>
922
923Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
924
925Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards.
926
927</details>
928
929<details>
930<summary><strong>Running Tests</strong></summary>
931
932Running 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:
933
934```sh
935$ npm install && npm test
936```
937
938</details>
939
940<details>
941<summary><strong>Building docs</strong></summary>
942
943_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
944
945To generate the readme, run the following command:
946
947```sh
948$ npm install -g verbose/verb#dev verb-generate-readme && verb
949```
950
951</details>
952
953### Related projects
954
955You might also be interested in these projects:
956
957* [braces](https://www.npmjs.com/package/braces): Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support… [more](https://github.com/micromatch/braces) | [homepage](https://github.com/micromatch/braces "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.")
958* [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/micromatch/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.")
959* [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.")
960* [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`")
961* [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/micromatch/nanomatch) | [homepage](https://github.com/micromatch/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)")
962
963### Contributors
964
965| **Commits** | **Contributor** |
966| --- | --- |
967| 475 | [jonschlinkert](https://github.com/jonschlinkert) |
968| 12  | [es128](https://github.com/es128) |
969| 8   | [doowb](https://github.com/doowb) |
970| 3   | [paulmillr](https://github.com/paulmillr) |
971| 2   | [TrySound](https://github.com/TrySound) |
972| 2   | [MartinKolarik](https://github.com/MartinKolarik) |
973| 2   | [Tvrqvoise](https://github.com/Tvrqvoise) |
974| 2   | [tunnckoCore](https://github.com/tunnckoCore) |
975| 1   | [amilajack](https://github.com/amilajack) |
976| 1   | [mrmlnc](https://github.com/mrmlnc) |
977| 1   | [devongovett](https://github.com/devongovett) |
978| 1   | [DianeLooney](https://github.com/DianeLooney) |
979| 1   | [UltCombo](https://github.com/UltCombo) |
980| 1   | [tomByrer](https://github.com/tomByrer) |
981| 1   | [fidian](https://github.com/fidian) |
982| 1   | [simlu](https://github.com/simlu) |
983| 1   | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) |
984
985### Author
986
987**Jon Schlinkert**
988
989* [GitHub Profile](https://github.com/jonschlinkert)
990* [Twitter Profile](https://twitter.com/jonschlinkert)
991* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
992
993### License
994
995Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert).
996Released under the [MIT License](LICENSE).
997
998***
999
1000_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 10, 2019._