Skip to content

Instantly share code, notes, and snippets.

@abozhilov
Created June 26, 2012 18:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save abozhilov/2997730 to your computer and use it in GitHub Desktop.
Save abozhilov/2997730 to your computer and use it in GitHub Desktop.
Wildcard to RegExp
/**
* Convert wildcard pattern to RegExp
* Pattern:
* * - Zero or more characters
* ? - Exactly one character
*
* @param {String} pattern Wildcard pattern
* @returns {RegExp} regular expression for wildcard matching
*/
function wc2reg(pattern) {
return RegExp('^' + pattern
.replace(/[\\$^.+()[\]{}|]/g, '\\$&')
.replace(/\?/g, '.')
.replace(/\*[*.]*/g, '(?:.*?)') + '$'
);
}
//Examples
wc2reg('*'); //^(?:.*?)$
wc2reg('*linux*.html'); //^(?:.*?)linux(?:.*?)\.html$
wc2reg('junk.???'); //^junk\....$
wc2reg(/^\w+@[a-zA-Z_]+\.[a-zA-Z]{2,3}$/.source); ///^\^\\w\+@\[a-zA-Z_\]\+\\\.\[a-zA-Z\]\{2,3\}\$$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment