Skip to content

Instantly share code, notes, and snippets.

@bitifet
Last active November 18, 2020 17:51
Show Gist options
  • Save bitifet/7f8e5dd67328667e4f9969eb385c5a81 to your computer and use it in GitHub Desktop.
Save bitifet/7f8e5dd67328667e4f9969eb385c5a81 to your computer and use it in GitHub Desktop.
Transform search patterns to regular expressions.
// 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