micromatch NPM version NPM monthly downloads NPM total downloads Linux Build Status Windows Build Status

Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.

Please consider following this project’s author, Jon Schlinkert, and consider starring the project to show your :heart: and support.

Table of Contents

Details - [Install](#install) - [Quickstart](#quickstart) - [Why use micromatch?](#why-use-micromatch) * [Matching features](#matching-features) - [Switching to micromatch](#switching-to-micromatch) * [From minimatch](#from-minimatch) * [From multimatch](#from-multimatch) - [API](#api) - [Options](#options) * [options.basename](#optionsbasename) * [options.bash](#optionsbash) * [options.cache](#optionscache) * [options.dot](#optionsdot) * [options.failglob](#optionsfailglob) * [options.ignore](#optionsignore) * [options.matchBase](#optionsmatchbase) * [options.nobrace](#optionsnobrace) * [options.nocase](#optionsnocase) * [options.nodupes](#optionsnodupes) * [options.noext](#optionsnoext) * [options.nonegate](#optionsnonegate) * [options.noglobstar](#optionsnoglobstar) * [options.nonull](#optionsnonull) * [options.nullglob](#optionsnullglob) * [options.snapdragon](#optionssnapdragon) * [options.sourcemap](#optionssourcemap) * [options.unescape](#optionsunescape) * [options.unixify](#optionsunixify) - [Extended globbing](#extended-globbing) * [extglobs](#extglobs) * [braces](#braces) * [regex character classes](#regex-character-classes) * [regex groups](#regex-groups) * [POSIX bracket expressions](#posix-bracket-expressions) - [Notes](#notes) * [Bash 4.3 parity](#bash-43-parity) * [Backslashes](#backslashes) - [Contributing](#contributing) - [Benchmarks](#benchmarks) * [Running benchmarks](#running-benchmarks) * [Latest results](#latest-results) - [About](#about)

Install

Install with npm:

$ npm install --save micromatch

Quickstart

var mm = require('micromatch');
mm(list, patterns[, options]);

The main export takes a list of strings and one or more glob patterns:

console.log(mm(['foo', 'bar', 'qux'], ['f*', 'b*'])); 
//=> ['foo', 'bar']

Use .isMatch() to get true/false:

console.log(mm.isMatch('foo', 'f*'));  
//=> true

Switching from minimatch and multimatch is easy!

Why use micromatch?

micromatch is a drop-in replacement for minimatch and multimatch

Matching features

You can mix and match these features to create whatever patterns you need!

Switching to micromatch

There is one notable difference between micromatch and minimatch in regards to how backslashes are handled. See the notes about backslashes for more information.

From minimatch

Use mm.isMatch() instead of minimatch():

mm.isMatch('foo', 'b*');
//=> false

Use mm.match() instead of minimatch.match():

mm.match(['foo', 'bar'], 'b*');
//=> 'bar'

From multimatch

Same signature:

mm(['foo', 'bar', 'baz'], ['f*', '*z']);
//=> ['foo', 'baz']

API

micromatch

The main function takes a list of strings and one or more glob patterns to use for matching.

Params

Example

var mm = require('micromatch');
mm(list, patterns[, options]);

console.log(mm(['a.js', 'a.txt'], ['*.js']));
//=> [ 'a.js' ]

.match

Similar to the main function, but pattern must be a string.

Params

Example

var mm = require('micromatch');
mm.match(list, pattern[, options]);

console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a'));
//=> ['a.a', 'a.aa']

.isMatch

Returns true if the specified string matches the given glob pattern.

Params

Example

var mm = require('micromatch');
mm.isMatch(string, pattern[, options]);

console.log(mm.isMatch('a.a', '*.a'));
//=> true
console.log(mm.isMatch('a.b', '*.a'));
//=> false

.some

Returns true if some of the strings in the given list match any of the given glob patterns.

Params

Example

var mm = require('micromatch');
mm.some(list, patterns[, options]);

console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
// true
console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
// false

.every

Returns true if every string in the given list matches any of the given glob patterns.

Params

Example

var mm = require('micromatch');
mm.every(list, patterns[, options]);

console.log(mm.every('foo.js', ['foo.js']));
// true
console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
// true
console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
// false
console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
// false

.any

Returns true if any of the given glob patterns match the specified string.

Params

Example

var mm = require('micromatch');
mm.any(string, patterns[, options]);

console.log(mm.any('a.a', ['b.*', '*.a']));
//=> true
console.log(mm.any('a.a', 'b.*'));
//=> false

.all

Returns true if all of the given patterns match the specified string.

Params

Example

var mm = require('micromatch');
mm.all(string, patterns[, options]);

console.log(mm.all('foo.js', ['foo.js']));
// true

console.log(mm.all('foo.js', ['*.js', '!foo.js']));
// false

console.log(mm.all('foo.js', ['*.js', 'foo.js']));
// true

console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
// true

.not

Returns a list of strings that do not match any of the given patterns.

Params

Example

var mm = require('micromatch');
mm.not(list, patterns[, options]);

console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
//=> ['b.b', 'c.c']

.contains

Returns true if the given string contains the given pattern. Similar to .isMatch but the pattern can match any part of the string.

Params

Example

var mm = require('micromatch');
mm.contains(string, pattern[, options]);

console.log(mm.contains('aa/bb/cc', '*b'));
//=> true
console.log(mm.contains('aa/bb/cc', '*d'));
//=> false

.matchKeys

Filter 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 instead.

Params

Example

var mm = require('micromatch');
mm.matchKeys(object, patterns[, options]);

var obj = { aa: 'a', ab: 'b', ac: 'c' };
console.log(mm.matchKeys(obj, '*b'));
//=> { ab: 'b' }

.matcher

Returns a memoized 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.

Params

Example

var mm = require('micromatch');
mm.matcher(pattern[, options]);

var isMatch = mm.matcher('*.!(*a)');
console.log(isMatch('a.a'));
//=> false
console.log(isMatch('a.b'));
//=> true

.capture

Returns an array of matches captured by pattern in string, ornull` if the pattern did not match.

Params

Example

var mm = require('micromatch');
mm.capture(pattern, string[, options]);

console.log(mm.capture('test/*.js', 'test/foo.js'));
//=> ['foo']
console.log(mm.capture('test/*.js', 'foo/bar.css'));
//=> null

.makeRe

Create a regular expression from the given glob pattern.

Params

Example

var mm = require('micromatch');
mm.makeRe(pattern[, options]);

console.log(mm.makeRe('*.js'));
//=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/

.braces

Expand the given brace pattern.

Params

Example

var mm = require('micromatch');
console.log(mm.braces('foo/{a,b}/bar'));
//=> ['foo/(a|b)/bar']

console.log(mm.braces('foo/{a,b}/bar', {expand: true}));
//=> ['foo/(a|b)/bar']

.create

Parses the given glob pattern and returns an array of abstract syntax trees (ASTs), with the compiled output and optional source map on each AST.

Params

Example

var mm = require('micromatch');
mm.create(pattern[, options]);

console.log(mm.create('abc/*.js'));
// [{ options: { source: 'string', sourcemap: true },
//   state: {},
//   compilers:
//    { ... },
//   output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js',
//   ast:
//    { type: 'root',
//      errors: [],
//      nodes:
//       [ ... ],
//      dot: false,
//      input: 'abc/*.js' },
//   parsingErrors: [],
//   map:
//    { version: 3,
//      sources: [ 'string' ],
//      names: [],
//      mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE',
//      sourcesContent: [ 'abc/*.js' ] },
//   position: { line: 1, column: 28 },
//   content: {},
//   files: {},
//   idx: 6 }]

.parse

Parse the given str with the given options.

Params

Example

var mm = require('micromatch');
mm.parse(pattern[, options]);

var ast = mm.parse('a/{b,c}/d');
console.log(ast);
// { type: 'root',
//   errors: [],
//   input: 'a/{b,c}/d',
//   nodes:
//    [ { type: 'bos', val: '' },
//      { type: 'text', val: 'a/' },
//      { type: 'brace',
//        nodes:
//         [ { type: 'brace.open', val: '{' },
//           { type: 'text', val: 'b,c' },
//           { type: 'brace.close', val: '}' } ] },
//      { type: 'text', val: '/d' },
//      { type: 'eos', val: '' } ] }

.compile

Compile the given ast or string with the given options.

Params

Example

var mm = require('micromatch');
mm.compile(ast[, options]);

var ast = mm.parse('a/{b,c}/d');
console.log(mm.compile(ast));
// { options: { source: 'string' },
//   state: {},
//   compilers:
//    { eos: [Function],
//      noop: [Function],
//      bos: [Function],
//      brace: [Function],
//      'brace.open': [Function],
//      text: [Function],
//      'brace.close': [Function] },
//   output: [ 'a/(b|c)/d' ],
//   ast:
//    { ... },
//   parsingErrors: [] }

.clearCache

Clear the regex cache.

Example

mm.clearCache();

Options

options.basename

Allow glob patterns without slashes to match a file path based on its basename. Same behavior as minimatch option matchBase.

Type: Boolean

Default: false

Example

mm(['a/b.js', 'a/c.md'], '*.js');
//=> []

mm(['a/b.js', 'a/c.md'], '*.js', {matchBase: true});
//=> ['a/b.js']

options.bash

Enabled 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 an other star.

Type: Boolean

Default: true

Example

var files = ['abc', 'ajz'];
console.log(mm(files, '[a-c]*'));
//=> ['abc', 'ajz']

console.log(mm(files, '[a-c]*', {bash: false}));

options.cache

Disable regex and function memoization.

Type: Boolean

Default: undefined

options.dot

Match dotfiles. Same behavior as minimatch option dot.

Type: Boolean

Default: false

options.failglob

Similar to the --failglob behavior in Bash, throws an error when no matches are found.

Type: Boolean

Default: undefined

options.ignore

String or array of glob patterns to match files to ignore.

Type: String|Array

Default: undefined

options.matchBase

Alias for options.basename.

options.nobrace

Disable expansion of brace patterns. Same behavior as minimatch option nobrace.

Type: Boolean

Default: undefined

See braces for more information about extended brace expansion.

options.nocase

Use a case-insensitive regex for matching files. Same behavior as minimatch.

Type: Boolean

Default: undefined

options.nodupes

Remove duplicate elements from the result array.

Type: Boolean

Default: undefined

Example

Example of using the unescape and nodupes options together:

mm.match(['a/b/c', 'a/b/c'], 'a/b/c');
//=> ['a/b/c', 'a/b/c']

mm.match(['a/b/c', 'a/b/c'], 'a/b/c', {nodupes: true});
//=> ['abc']

options.noext

Disable extglob support, so that extglobs are regarded as literal characters.

Type: Boolean

Default: undefined

Examples

mm(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)');
//=> ['a/b', 'a/!(z)']

mm(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', {noext: true});
//=> ['a/!(z)'] (matches only as literal characters)

options.nonegate

Disallow negation (!) patterns, and treat leading ! as a literal character to match.

Type: Boolean

Default: undefined

options.noglobstar

Disable matching with globstars (**).

Type: Boolean

Default: undefined

mm(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**');
//=> ['a/b', 'a/b/c', 'a/b/c/d']

mm(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true});
//=> ['a/b']

options.nonull

Alias for options.nullglob.

options.nullglob

If true, when no matches are found the actual (arrayified) glob pattern is returned instead of an empty array. Same behavior as minimatch option nonull.

Type: Boolean

Default: undefined

options.snapdragon

Pass your own instance of snapdragon, to customize parsers or compilers.

Type: Object

Default: undefined

options.sourcemap

Generate a source map by enabling the sourcemap option with the .parse, .compile, or .create methods.

(Note that sourcemaps are currently not enabled for brace patterns)

Examples

var mm = require('micromatch');
var pattern = '*(*(of*(a)x)z)';

var res = mm.create('abc/*.js', {sourcemap: true});
console.log(res.map);
// { version: 3,
//   sources: [ 'string' ],
//   names: [],
//   mappings: 'AAAA,GAAG,EAAC,iBAAC,EAAC,EAAE',
//   sourcesContent: [ 'abc/*.js' ] }

var ast = mm.parse('abc/**/*.js');
var res = mm.compile(ast, {sourcemap: true});
console.log(res.map);
// { version: 3,
//   sources: [ 'string' ],
//   names: [],
//   mappings: 'AAAA,GAAG,EAAC,2BAAE,EAAC,iBAAC,EAAC,EAAE',
//   sourcesContent: [ 'abc/**/*.js' ] }

var ast = mm.parse(pattern);
var res = mm.compile(ast, {sourcemap: true});
console.log(res.map);
// { version: 3,
//   sources: [ 'string' ],
//   names: [],
//   mappings: 'AAAA,CAAE,CAAE,EAAE,CAAE,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC',
//   sourcesContent: [ '*(*(of*(a)x)z)' ] }

options.unescape

Remove backslashes from returned matches.

Type: Boolean

Default: undefined

Example

In this example we want to match a literal *:

mm.match(['abc', 'a\\*c'], 'a\\*c');
//=> ['a\\*c']

mm.match(['abc', 'a\\*c'], 'a\\*c', {unescape: true});
//=> ['a*c']

options.unixify

Convert path separators on returned files to posix/unix-style forward slashes.

Type: Boolean

Default: true on windows, false everywhere else

Example

mm.match(['a\\b\\c'], 'a/**');
//=> ['a/b/c']

mm.match(['a\\b\\c'], {unixify: false});
//=> ['a\\b\\c']

Extended globbing

Micromatch also supports extended globbing features.

extglobs

Extended globbing, as described by the bash man page:

pattern regex equivalent description
?(pattern) (pattern)? Matches zero or one occurrence of the given patterns
*(pattern) (pattern)* Matches zero or more occurrences of the given patterns
+(pattern) (pattern)+ Matches one or more occurrences of the given patterns
@(pattern) (pattern) * Matches one of the given patterns
!(pattern) N/A (equivalent regex is much more complicated) Matches anything except one of the given patterns

* Note that @ isn’t a RegEx character.

Powered by extglob. Visit that library for the full range of options or to report extglob related issues.

braces

Brace patterns can be used to match specific ranges or sets of characters. For example, the pattern */{1..3}/* would match any of following strings:

foo/1/bar
foo/2/bar
foo/3/bar
baz/1/qux
baz/2/qux
baz/3/qux

Visit braces to see the full range of features and options related to brace expansion, or to create brace matching or expansion related issues.

regex character classes

Given the list: ['a.js', 'b.js', 'c.js', 'd.js', 'E.js']:

Learn about regex character classes.

regex groups

Given ['a.js', 'b.js', 'c.js', 'd.js', 'E.js']:

As 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.

POSIX bracket expressions

POSIX brackets are intended to be more user-friendly than regex character classes. This of course is in the eye of the beholder.

Example

mm.isMatch('a1', '[[:alpha:][:digit:]]');
//=> true

mm.isMatch('a1', '[[:alpha:][:alpha:]]');
//=> false

See expand-brackets for more information about bracket expressions.


Notes

Bash 4.3 parity

Whenever possible matching behavior is based on behavior Bash 4.3, which is mostly consistent with minimatch.

However, 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.

Backslashes

There is an important, notable difference between minimatch and micromatch in regards to how backslashes are handled in glob patterns.

We made this decision for micromatch for a couple of reasons:

A note about joining paths to globs

Note 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 \\.

In 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.

Contributing

All contributions are welcome! Please read the contributing guide to get started.

Bug reports

Please create an issue if you encounter a bug or matching behavior that doesn’t seem correct. If you find a matching-related issue, please:

Platform issues

It’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).

Benchmarks

Running benchmarks

Install dev dependencies:

npm i -d && npm run benchmark

Latest results

As of February 18, 2018 (longer bars are better):

# braces-globstar-large-list (485691 bytes)
  micromatch ██████████████████████████████████████████████████ (517 ops/sec ±0.49%)
  minimatch  █ (18.92 ops/sec ±0.54%)
  multimatch █ (18.94 ops/sec ±0.62%)

  micromatch is faster by an avg. of 2,733%

# braces-multiple (3362 bytes)
  micromatch ██████████████████████████████████████████████████ (33,625 ops/sec ±0.45%)
  minimatch   (2.92 ops/sec ±3.26%)
  multimatch  (2.90 ops/sec ±2.76%)

  micromatch is faster by an avg. of 1,156,935%

# braces-range (727 bytes)
  micromatch █████████████████████████████████████████████████ (155,220 ops/sec ±0.56%)
  minimatch  ██████ (20,186 ops/sec ±1.27%)
  multimatch ██████ (19,809 ops/sec ±0.60%)

  micromatch is faster by an avg. of 776%

# braces-set (2858 bytes)
  micromatch █████████████████████████████████████████████████ (24,354 ops/sec ±0.92%)
  minimatch  █████ (2,566 ops/sec ±0.56%)
  multimatch ████ (2,431 ops/sec ±1.25%)

  micromatch is faster by an avg. of 975%

# globstar-large-list (485686 bytes)
  micromatch █████████████████████████████████████████████████ (504 ops/sec ±0.45%)
  minimatch  ███ (33.36 ops/sec ±1.08%)
  multimatch ███ (33.19 ops/sec ±1.35%)

  micromatch is faster by an avg. of 1,514%

# globstar-long-list (90647 bytes)
  micromatch ██████████████████████████████████████████████████ (2,694 ops/sec ±1.08%)
  minimatch  ████████████████ (870 ops/sec ±1.09%)
  multimatch ████████████████ (862 ops/sec ±0.84%)

  micromatch is faster by an avg. of 311%

# globstar-short-list (182 bytes)
  micromatch ██████████████████████████████████████████████████ (328,921 ops/sec ±1.06%)
  minimatch  █████████ (64,808 ops/sec ±1.42%)
  multimatch ████████ (57,991 ops/sec ±2.11%)

  micromatch is faster by an avg. of 536%

# no-glob (701 bytes)
  micromatch █████████████████████████████████████████████████ (415,935 ops/sec ±0.36%)
  minimatch  ███████████ (92,730 ops/sec ±1.44%)
  multimatch █████████ (81,958 ops/sec ±2.13%)

  micromatch is faster by an avg. of 476%

# star-basename-long (12339 bytes)
  micromatch █████████████████████████████████████████████████ (7,963 ops/sec ±0.36%)
  minimatch  ███████████████████████████████ (5,072 ops/sec ±0.83%)
  multimatch ███████████████████████████████ (5,028 ops/sec ±0.40%)

  micromatch is faster by an avg. of 158%

# star-basename-short (349 bytes)
  micromatch ██████████████████████████████████████████████████ (269,552 ops/sec ±0.70%)
  minimatch  ██████████████████████ (122,457 ops/sec ±1.39%)
  multimatch ████████████████████ (110,788 ops/sec ±1.99%)

  micromatch is faster by an avg. of 231%

# star-folder-long (19207 bytes)
  micromatch █████████████████████████████████████████████████ (3,806 ops/sec ±0.38%)
  minimatch  ████████████████████████████ (2,204 ops/sec ±0.32%)
  multimatch ██████████████████████████ (2,020 ops/sec ±1.07%)

  micromatch is faster by an avg. of 180%

# star-folder-short (551 bytes)
  micromatch ██████████████████████████████████████████████████ (249,077 ops/sec ±0.40%)
  minimatch  ███████████ (59,431 ops/sec ±1.67%)
  multimatch ███████████ (55,569 ops/sec ±1.43%)

  micromatch is faster by an avg. of 433%

About

Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](.github/contributing.md) 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: ```sh $ npm install && npm test ```
Building docs _(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.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ```

You might also be interested in these projects:

Contributors

Commits Contributor
457 jonschlinkert
12 es128
8 doowb
3 paulmillr
2 TrySound
2 MartinKolarik
2 charlike-old
1 amilajack
1 mrmlnc
1 devongovett
1 DianeLooney
1 UltCombo
1 tomByrer
1 fidian

Author

Jon Schlinkert

License

Copyright © 2018, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.6.0, on February 18, 2018.