Enhance the wildcard to regexp conversion

This commit is contained in:
Raymond Feng 2014-06-18 12:37:49 -07:00
parent a487eb57cd
commit b3b29d7313
1 changed files with 29 additions and 4 deletions

View File

@ -363,8 +363,34 @@ function applyFilter(filter) {
return pass;
}
function replaceAll(string, find, replace) {
return string.replace(new RegExp(find, 'g'), replace);
function toRegExp(pattern) {
if (pattern instanceof RegExp) {
return pattern;
}
var regex = '';
pattern = pattern.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
for (var i = 0, n = pattern.length; i < n; i++) {
var char = pattern.charAt(i);
if (char === '\\') {
i++; // Skip to next char
if (i < n) {
regex += pattern.charAt(i);
}
continue;
} else if (char === '%') {
regex += '.*';
} else if (char === '_') {
regex += '.';
} else if (char === '.') {
regex += '\\.';
} else if (char === '*') {
regex += '\\*';
}
else {
regex += char;
}
}
return regex;
}
function test(example, value) {
@ -394,8 +420,7 @@ function applyFilter(filter) {
var like = example.like || example.nlike;
if (typeof like === 'string') {
like = replaceAll(like, '%', '.*');
like = replaceAll(like, '_', '.');
like = toRegExp(like);
}
if (example.like) {
return !!new RegExp(like).test(value);