如何在 angularjs 中使用通配符搜索?
how to use Wildcard search in angularjs?
我想实现通配符搜索。现在写下我正在做的是:
var patt = new RegExp(input);
if(patt.test(searchString))
$scope.filteredModel.push(searchString);
但这并没有给出通配符搜索结果。即如果我输入 v*
,我应该得到所有 starting 和 v
的字符串。但在这种情况下,因为我使用的是 regExp
,所以我得到了所有字符串(因为 v*
表示 0 次或更多 次 v
的出现) .我该如何自定义它?
如果您使用的是正则表达式,也许您可以尝试使用不同字符的简写版本。
Some implementations of regular expressions allow you to use shorthand versions for commonly used sequences, they are:
\d, a digit ([0-9])
\D, a non-digit ([^0-9])
\w, a word (alphanumeric) ([a-zA-Z0-9])
\W, a non-word ([^a-zA-Z0-9])
\s, a whitespace ([ \t\n\r\f])
\S, a non-whitespace ([^ \t\n\r\f])
您接受用户输入并将其转换为等效的通配符。 *
应该变成 .*
并且您应该在开头添加 ^
以仅匹配以给定模式开头的内容:
var patt = new RegExp('^' + input.replace(/\*/g, '.*'));
现在您可以使用 patt
进行测试并获得所需的结果。
您可能还想转义正则表达式中的其他特殊字符:
var specialCharacters = /([.\+?[^\]$(){}=!<>|:-])/g;
var patt = new RegExp('^' + input.replace(specialCharacters, "\").replace(/\*/g, '.*'));
这可能看起来很可怕,但它所做的只是在其中任何一个前面添加 \
:. \ + ? [ ^ ] $ ( ) { } = ! < > | : -
。这样,如果用户输入 v*ABC+
,它将尝试匹配以 v
开头并以 ABC+
结尾的内容,而不是以 ABC
结尾和可变数量的 [=22] =]就像 ABCCCCCCC
.
我想实现通配符搜索。现在写下我正在做的是:
var patt = new RegExp(input);
if(patt.test(searchString))
$scope.filteredModel.push(searchString);
但这并没有给出通配符搜索结果。即如果我输入 v*
,我应该得到所有 starting 和 v
的字符串。但在这种情况下,因为我使用的是 regExp
,所以我得到了所有字符串(因为 v*
表示 0 次或更多 次 v
的出现) .我该如何自定义它?
如果您使用的是正则表达式,也许您可以尝试使用不同字符的简写版本。
Some implementations of regular expressions allow you to use shorthand versions for commonly used sequences, they are:
\d, a digit ([0-9])
\D, a non-digit ([^0-9])
\w, a word (alphanumeric) ([a-zA-Z0-9])
\W, a non-word ([^a-zA-Z0-9])
\s, a whitespace ([ \t\n\r\f])
\S, a non-whitespace ([^ \t\n\r\f])
您接受用户输入并将其转换为等效的通配符。 *
应该变成 .*
并且您应该在开头添加 ^
以仅匹配以给定模式开头的内容:
var patt = new RegExp('^' + input.replace(/\*/g, '.*'));
现在您可以使用 patt
进行测试并获得所需的结果。
您可能还想转义正则表达式中的其他特殊字符:
var specialCharacters = /([.\+?[^\]$(){}=!<>|:-])/g;
var patt = new RegExp('^' + input.replace(specialCharacters, "\").replace(/\*/g, '.*'));
这可能看起来很可怕,但它所做的只是在其中任何一个前面添加 \
:. \ + ? [ ^ ] $ ( ) { } = ! < > | : -
。这样,如果用户输入 v*ABC+
,它将尝试匹配以 v
开头并以 ABC+
结尾的内容,而不是以 ABC
结尾和可变数量的 [=22] =]就像 ABCCCCCCC
.