Regex Wildcard for Array Search

余生颓废 提交于 2019-12-08 07:18:16

问题


I have a json array that I currently search through by flipping a boolean flag:

for (var c=0; c<json.archives.length; c++) {
if ((json.archives[c].archive_num.toLowerCase().indexOf(query)>-1)){
inSearch = true;
} }

And I have been trying to create a wildcard regex search by using a special character '*' but I haven't been able to loop through the array with my wildcard.

So what I'm trying to accomplish is when query = '199*', replace the '*' with /[\w]/ and essentially search for 1990,1991,1992,1993,1994 + ... + 199a,199b, etc.

All my attempts turn literal and I end up searching '199/[\w]/'.

Any ideas on how to create a regex wildcard to search an array?

Thanks!


回答1:


You should write something like this:

var query = '199*';
var queryPattern = query.replace(/\*/g, '\\w');
var queryRegex = new RegExp(queryPattern, 'i');

Next, to check each word:

if(json.archives[c].archive_num.match(queryRegex))

Notes:

  • Consider using ? instead of *, * usually stands for many letters, not one.
  • Note that we have to escape the backslash so it will create a valid string literal. The string '\w' is the same as the string w - the escape is ignored in this case.
  • You don't need delimiters (/.../) when creating a RegExp object from a string.
  • [\w] is the same as \w. Yeah, minor one.
  • You can avoid partial matching by using the pattern:

    var queryPattern = '\\b' query.replace(/\*/g, '\\w') + '\\b';
    

    Or, similarly:

    var queryPattern = '^' query.replace(/\*/g, '\\w') + '$';
    



回答2:


var qre = query.replace(/[^\w\s]/g, "\\$&") // escape special chars so they dont mess up the regex
               .replace("\\*", "\\w");      // replace the now escaped * with '\w'

qre = new RegExp(qre, "i"); // create a regex object from the built string
if(json.archives[c].archive_num.match(qre)){
    //...
}


来源:https://stackoverflow.com/questions/6333246/regex-wildcard-for-array-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!