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

Glob matching for javascript/node.js. A 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 with npm:

$ npm install --save micromatch

Quickstart

const micromatch = require('micromatch');
// micromatch(list, patterns[, options]);

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

console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['f*', 'b*'])) //=> ['foo', 'bar', 'baz']
console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['*', '!b*'])) //=> ['foo', 'qux']

Use .isMatch() to for boolean matching:

console.log(micromatch.isMatch('foo', 'f*')) //=> true
console.log(micromatch.isMatch('foo', ['b*', 'f*'])) //=> true

Switching from minimatch and multimatch is easy!


Why use micromatch?

micromatch is a 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 micromatch.isMatch() instead of minimatch():

console.log(micromatch.isMatch('foo', 'b*')); //=> false

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

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

From multimatch

Same signature:

console.log(micromatch(['foo', 'bar', 'baz'], ['f*', '*z'])); //=> ['foo', 'baz']

API

Params

Example

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

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

.matcher

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

Params

Example

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

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

.isMatch

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

Params

Example

const mm = require('micromatch');
// mm.isMatch(string, patterns[, options]);

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

.not

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

Params

Example

const 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

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

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

.some

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

Params

Example

const 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

const 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

.all

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

Params

Example

const 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

.capture

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

Params

Example

const 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

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

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

.scan

Scan a glob pattern to separate the pattern into segments. Used by the split method.

Params

Example

const mm = require('micromatch');
const state = mm.scan(pattern[, options]);

.parse

Parse a glob pattern to create the source string for a regular expression.

Params

Example

const mm = require('micromatch');
const state = mm(pattern[, options]);

.braces

Process the given brace pattern.

Params

Example

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

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

Options

Option Type Default value Description
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.
bash boolean false Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (**).
capture boolean undefined Return regex matches in supporting methods.
contains boolean undefined Allows glob to match any part of the given string(s).
cwd string process.cwd() Current working directory. Used by picomatch.split()
debug boolean undefined Debug regular expressions when an error is thrown.
dot boolean false Match dotfiles. Otherwise dotfiles are ignored unless a . is explicitly defined in the pattern.
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.
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.
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.
flags boolean undefined Regex flags to use in the generated regex. If defined, the nocase option will be overridden.
format function undefined Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc.
ignore array\|string undefined One or more glob patterns for excluding strings that should not be matched from the result.
keepQuotes boolean false Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes.
literalBrackets boolean undefined When true, brackets in the glob pattern will be escaped so that only literal brackets will be matched.
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.
matchBase boolean false Alias for basename
maxLength boolean 65536 Limit the max length of the input string. An error is thrown if the input string is longer than this value.
nobrace boolean false Disable brace matching, so that {a,b} and {1..3} would be treated as literal characters.
nobracket boolean undefined Disable matching with regex brackets.
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.
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.
noext boolean false Alias for noextglob
noextglob boolean false Disable support for matching with extglobs (like +(a\|b))
noglobstar boolean false Disable support for matching nested directories with globstars (**)
nonegate boolean false Disable support for negating with leading !
noquantifiers boolean false Disable support for regex quantifiers (like a{1,2}) and treat them as brace patterns to be expanded.
onIgnore function undefined Function to be called on ignored items.
onMatch function undefined Function to be called on matched items.
onResult function undefined Function to be called on all items, regardless of whether or not they are matched or ignored.
posix boolean false Support POSIX character classes ("posix brackets").
posixSlashes boolean undefined Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself
prepend boolean undefined String to prepend to the generated regex used for matching.
regex boolean false Use regular expression rules for + (instead of matching literal +), and for stars that follow closing parentheses or brackets (as in )* and ]*).
strictBrackets boolean undefined Throw an error if brackets, braces, or parens are imbalanced.
strictSlashes boolean undefined When true, picomatch won't match trailing slashes with single stars.
unescape boolean undefined Remove preceding backslashes from escaped glob characters before creating the regular expression to perform matches.
unixify boolean undefined Alias for posixSlashes, for backwards compatitibility.

Options Examples

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

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

micromatch(['a/b.js', 'a/c.md'], '*.js', { basename: 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 any other star.

Type: Boolean

Default: true

Example

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

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

options.expandRange

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 numeric folder name between 01 and 25, with leading zeros.

const fill = require('fill-range');
const regex = micromatch.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

options.format

Type: 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')) //=> true

options.ignore

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

Type: String|Array

Default: undefined

const isMatch = micromatch.matcher('*', { ignore: 'f*' });
console.log(isMatch('foo')) //=> false
console.log(isMatch('bar')) //=> true
console.log(isMatch('baz')) //=> true

options.matchBase

Alias for options.basename.

options.noextglob

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

Type: Boolean

Default: undefined

Examples

console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)'));
//=> ['a/b', 'a/!(z)']

console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', { noextglob: 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

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

micromatch(['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.onIgnore

const onIgnore = ({ glob, regex, input, output }) => {
  console.log({ glob, regex, input, output });
  // { glob: '*', regex: /^(?:(?!\.)(?=.)[^\/]*?\/?)$/, input: 'foo', output: 'foo' }
};

const isMatch = micromatch.matcher('*', { onIgnore, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');

options.onMatch

const onMatch = ({ glob, regex, input, output }) => {
  console.log({ input, output });
  // { input: 'some\\path', output: 'some/path' }
  // { input: 'some\\path', output: 'some/path' }
  // { input: 'some\\path', output: 'some/path' }
};

const isMatch = micromatch.matcher('**', { onMatch, posixSlashes: true });
isMatch('some\\path');
isMatch('some\\path');
isMatch('some\\path');

options.onResult

const onResult = ({ glob, regex, input, output }) => {
  console.log({ glob, regex, input, output });
};

const isMatch = micromatch('*', { onResult, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');

options.posixSlashes

Convert path separators on returned files to posix/unix-style forward slashes. Aliased as unixify for backwards compatibility.

Type: Boolean

Default: true on windows, false everywhere else.

Example

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

console.log(micromatch.match(['a\\b\\c'], { posixSlashes: false }));
//=> ['a\\b\\c']

options.unescape

Remove backslashes from escaped glob characters before creating the regular expression to perform matches.

Type: Boolean

Default: undefined

Example

In this example we want to match a literal *:

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

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



Extended globbing

Micromatch supports the following 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.

Braces

Brace patterns can be used to match specific ranges or sets of characters.

Example

The pattern {f,b}*/{1..3}/{b,q}* 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

console.log(micromatch.isMatch('a1', '[[:alpha:][:digit:]]')) //=> true
console.log(micromatch.isMatch('a1', '[[:alpha:][:alpha:]]')) //=> false

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.

To solve this, you might be inspired to do something like 'foo\\*'.replace(/\\/g, '/'), but this causes another, potentially much more serious, problem.

Benchmarks

Running benchmarks

Install dependencies for running benchmarks:

$ cd bench && npm install 

Run the benchmarks:

$ npm run bench

Latest results

As of April 10, 2019 (longer bars are better):

# .makeRe star
  micromatch x 1,724,735 ops/sec ±1.69% (87 runs sampled))
  minimatch x 649,565 ops/sec ±1.93% (91 runs sampled)

# .makeRe star; dot=true
  micromatch x 1,302,127 ops/sec ±1.43% (92 runs sampled)
  minimatch x 556,242 ops/sec ±0.71% (86 runs sampled)

# .makeRe globstar
  micromatch x 1,393,992 ops/sec ±0.71% (89 runs sampled)
  minimatch x 1,112,801 ops/sec ±2.02% (91 runs sampled)

# .makeRe globstars
  micromatch x 1,419,097 ops/sec ±0.34% (94 runs sampled)
  minimatch x 541,207 ops/sec ±1.66% (93 runs sampled)

# .makeRe with leading star
  micromatch x 1,247,825 ops/sec ±0.97% (94 runs sampled)
  minimatch x 489,660 ops/sec ±0.63% (94 runs sampled)

# .makeRe - braces
  micromatch x 206,301 ops/sec ±1.62% (81 runs sampled))
  minimatch x 115,986 ops/sec ±0.59% (94 runs sampled)

# .makeRe braces - range (expanded)
  micromatch x 27,782 ops/sec ±0.79% (88 runs sampled)
  minimatch x 4,683 ops/sec ±1.20% (92 runs sampled)

# .makeRe braces - range (compiled)
  micromatch x 134,056 ops/sec ±2.73% (77 runs sampled))
  minimatch x 977 ops/sec ±0.85% (91 runs sampled)d)

# .makeRe braces - nested ranges (expanded)
  micromatch x 18,353 ops/sec ±0.95% (91 runs sampled)
  minimatch x 4,514 ops/sec ±1.04% (93 runs sampled)

# .makeRe braces - nested ranges (compiled)
  micromatch x 38,916 ops/sec ±1.85% (82 runs sampled)
  minimatch x 980 ops/sec ±0.54% (93 runs sampled)d)

# .makeRe braces - set (compiled)
  micromatch x 141,088 ops/sec ±1.70% (70 runs sampled))
  minimatch x 43,385 ops/sec ±0.87% (93 runs sampled)

# .makeRe braces - nested sets (compiled)
  micromatch x 87,272 ops/sec ±2.85% (71 runs sampled))
  minimatch x 25,327 ops/sec ±1.59% (86 runs sampled)

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

About

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 test
Building 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 && verb

Related projects

You might also be interested in these projects:

Contributors

Commits Contributor
475 jonschlinkert
12 es128
8 doowb
3 paulmillr
2 TrySound
2 MartinKolarik
2 Tvrqvoise
2 tunnckoCore
1 amilajack
1 mrmlnc
1 devongovett
1 DianeLooney
1 UltCombo
1 tomByrer
1 fidian
1 simlu
1 wtgtybhertgeghgtwtg

Author

Jon Schlinkert

License

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


This file was generated by verb-generate-readme, v0.8.0, on April 10, 2019.