Last active
November 18, 2020 17:51
-
-
Save bitifet/7f8e5dd67328667e4f9969eb385c5a81 to your computer and use it in GitHub Desktop.
Transform search patterns to regular expressions.
This file contains 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
// wildcards(pattern [, modifiers]) | |
// ================================ | |
// | |
// Transform search patterns with wildcards ('*' and '?') | |
// to suitable regular expresions. | |
// | |
// CAUTION: Pre-wrap with '*' (if needed). | |
// | |
// @@ Examples: @@ // | |
// @@ --------- @@ // | |
// @@ wildcards('list_*.htm*', 'i') // Generates /list_.*\.htm/i @@ // | |
// @@ wildcards('mate? roca*', 'i') // Matches "mateu..." and "mateo..." @@ // | |
// @@ wildcards(str+'*', 'i') // Allow for incremental search. @@ // | |
// @@ wildcards('*'str+'*', 'i') // Get even partial matchings. @@ // | |
// | |
function wildcards(pattern, modifiers) {//{{{ | |
const src = [...pattern].map(function(digit) { | |
switch (digit) { | |
case "*": return ".*"; | |
case "?": return "."; | |
default: | |
return ( | |
digit.match(/[\w\s,]/) ? digit | |
: "\\"+digit | |
); | |
}; | |
}); | |
return new RegExp( | |
['^', ...src, '$'].join("") | |
, modifiers | |
); | |
};//}}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment