Created
June 26, 2012 18:23
-
-
Save abozhilov/2997730 to your computer and use it in GitHub Desktop.
Wildcard to RegExp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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