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; return pass;
} }
function replaceAll(string, find, replace) { function toRegExp(pattern) {
return string.replace(new RegExp(find, 'g'), replace); 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) { function test(example, value) {
@ -394,8 +420,7 @@ function applyFilter(filter) {
var like = example.like || example.nlike; var like = example.like || example.nlike;
if (typeof like === 'string') { if (typeof like === 'string') {
like = replaceAll(like, '%', '.*'); like = toRegExp(like);
like = replaceAll(like, '_', '.');
} }
if (example.like) { if (example.like) {
return !!new RegExp(like).test(value); return !!new RegExp(like).test(value);