JS正则表达式跳过其他所有匹配项 [英] JS regex skips every other match

查看:40
本文介绍了JS正则表达式跳过其他所有匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到JS中的RegExp对象有一些奇怪的行为.我正在尝试将查询字符串与搜索自动完成功能的单词开头进行匹配.在遍历一个名称数组并返回匹配项时,正则表达式只会在所有其他预期匹配项上命中.

I'm seeing some strange behavior with a RegExp object in JS. I'm attempting to match a query string against the beginnings of words for a search autocomplete function. While iterating over an array of names and returning the matches, the regex only hits on every other expected match.

var words = [
                "catherine",
                "caterpillar", 
                "nice catch", 
                "fat cat", 
                "catalina"
            ],
            re = new RegExp('\\bcat', 'gi'),
            matches = [],
            results, i;

for (i=0; i<words.length; i++) {
    if (re.exec(words[i])) {
        matches.push(words[i]);
    }
}

console.log(matches);

此代码返回 ["catherine","nice catch","catalina"] .无论元素的顺序如何,行为都是相同的.如果我在每次迭代中都重新创建此RegExp对象(例如, re = new RegExp('\\ bcat','gi')for循环),它可以按预期工作并返回所有数组项,但是我真的不想每次都这样做.

This code returns ["catherine", "nice catch", "catalina"]. Behavior is the same no matter what order the elements are in. If I re-create this RegExp object in every iteration (e.g. re = new RegExp('\\bcat', 'gi') inside the for loop), it works as expected and returns all the array items, but I'd really rather not have to do that for every pass.

我对正则表达式不太熟悉-这是我的正则表达式的问题吗?我忘记了分隔符或其他东西吗?还是仅仅是另一个JS怪癖?

I'm not too familiar with regular expressions - is this a problem with my regex? Did I forget a delimiter or something? Or is it just another JS quirk?

推荐答案

在RegExp对象上调用 exec 时,它将维护一个 lastIndex 属性,该属性包含以前的索引,位于您的正则表达式匹配字符串.下次尝试使用 exec 进行匹配时,即使您正在搜索其他字符串,它也只会开始查看索引 lastIndex + 1 .

When you call exec on a RegExp object it maintains a lastIndex property that contains the previous index at which your regex matched the string. The next time you attempt to match using exec it will only start looking at index lastIndex + 1, even if you are searching in a different string.

为防止这种情况,您可以在循环的每次迭代中将 re.lastIndex 设置为 -1 ,或者在创建RegExp时仅删除全局标志.

To prevent this, you can set re.lastIndex to -1 on each iteration of the loop, or just drop the global flag when creating the RegExp.

这篇关于JS正则表达式跳过其他所有匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆