简体   繁体   English

Javascript:通配符正则表达式搜索

[英]Javascript: Wildcard regex search

I need to filter an array of string with a wildcard regex: 我需要使用通配符正则表达式过滤字符串数组:

// my search key
var myKeyword = 'bar';

// my search list
var strings = ['foo', 'bar', 'foobar', 'barfoo', 'hello', 'java', 'script', 'javascript'];

// my results
var results = [];

// the regexp, I don't understand
var regex = new RegExp(\*/, myKeyword);

// the for loop
for (var i = 0; i < strings.length; i++) {
    if (regex.test(strings[i]) {
        results.push(strings[i]);
    }
}

console.log(results); // prints ['bar', 'foobar', 'barfoo']

So how do I fix the regex? 那么我该如何修复正则表达式呢?

If you want to do it with a regex, do it like this: 如果要使用正则表达式执行此操作,请执行以下操作:

var regex = new RegExp(keyword);
// if you want it case-insensitive:
var regex = new RegExp(keyword, 'i');

This will break if the keyword contains any regex-specific characters such as [ or * . 如果关键字包含任何正则表达式特定的字符,例如[*则这将中断。 You need to write a function to escape these characters if that's a problem for you. 如果您遇到问题,则需要编写一个函数来转义这些字符。

However, you can solve your problem much easier by using strings[i].indexOf(keyword) != -1 to test if the keyword is in the string or not - without using a regex at all. 但是,通过使用strings[i].indexOf(keyword) != -1来测试关键字是否在字符串中,可以更轻松地解决问题-根本不需要使用正则表达式。

Not too sure what exactly you're trying to do here. 不太清楚您要在这里做什么。 Javascript does have literal REs so you could just do: Javascript确实具有文字RE,因此您可以执行以下操作:

var regex = /foo/;

which is just a nicer way of doing: 这只是一个更好的方法:

var regex = new RegExp( 'foo' );

(but in the second case, the 'foo' could be a string argument being passed in. (但在第二种情况下,“ foo”可能是传入的字符串参数。

You don't need any leading/trailing wildcards on a regular expression. 您在正则表达式上不需要任何前导/后缀通配符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM