Skip to content

Instantly share code, notes, and snippets.

@BriSeven
Created May 15, 2012 08:05
Show Gist options
  • Save BriSeven/2699916 to your computer and use it in GitHub Desktop.
Save BriSeven/2699916 to your computer and use it in GitHub Desktop.
Convert a unix style globbing pattern to a regular expression
//based on fnmatch.py
String.prototype.escape = function () {
"use strict";
var escapable = /[.\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'\.': '\\.',
'"': '\\"',
'\\': '\\\\'
};
function escapechar(a) {
var c = meta[a];
return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}
return this.replace(escapable, escapechar);
};
function translate(pat) {
//Translate a shell PATTERN to a regular expression.
//There is no way to quote meta-characters.
"use strict";
var i=0, j, n = pat.length || 0,
res, c, stuff;
res = '^';
while (i < n) {
c = pat[i];
i = i + 1;
if (c === '*') {
res = res + '.*';
} else if (c === '?') {
res = res + '.';
} else if (c === '[') {
j = i;
if (j < n && pat[j] === '!') {
j = j + 1;
}
if (j < n && pat[j] === ']') {
j = j + 1;
}
while (j < n && pat[j] !== ']') {
j = j + 1;
}
if (j >= n) {
res = res + '\\[';
} else {
stuff = pat.slice(i, j).replace('\\', '\\\\');
i = j + 1;
if (stuff[0] === '!') {
stuff = '^' + stuff.slice(1);
} else if (stuff[0] === '^') {
stuff = '\\' + stuff;
}
res = res + '[' + stuff + ']';
}
} else {
res = res + (c).escape();
}
}
return res + '$';
}
exports.translate = translate;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment