改进Regex以匹配列表中的重复项

时间:2011-09-17 23:27:56

标签: javascript regex

我正在使用正则表达式在列表中查找重复项。它只是一个简短的逗号分隔列表,性能不是问题,所以没有必要告诉我不应该因为这些原因使用正则表达式。

// returns a match because some is repeated
"some,thing,here,some,whatever".match(/(^|,)(.+?)(,|,.+,)\2(,|$)/g)

问题...

  1. 这个正则表达式可以改进吗?
  2. 是否涵盖逗号不在单独字符串中的所有可能情况
  3. 有没有更好的(最好是更具可读性和更有效率)的方法呢?

2 个答案:

答案 0 :(得分:1)

如果我想在逗号分隔列表中找到重复项,我会这样做,使用对象的哈希功能来累积唯一值并检测重复项:

function getDups(list) {
    var data = list.split(",");
    var uniques = {}, dups = {}, item, uniqueList = [];
    for (var i = 0; i < data.length; i++) {
        item = data[i];
        if (uniques[item]) {
            // found dup
            dups[item] = true;
        } else {
            // found unique item
            uniques[item] = true;
        }
    }
    // at the end here, you'd have an object called uniques with all the unique items in it
    // you could turn that back into an array easily if you wanted to
    // Since it uses the object hash for dup detection, it scales to large numbers of items just fine
    // you can return whatever you want here (a new list, a list of dups, etc...)
    // in this implementation, I chose to return an array of unique values
    for (var key in uniques) {
        uniqueList.push(key);
    }
    return(uniqueList);    // return array of unique values
}

var list = "some,thing,here,some,whatever";
getDups(list);

这是一个显示它有效的jsFiddle:http://jsfiddle.net/jfriend00/NGQCz/

这种类型的实现可以很好地适应大量单词,因为重复检测相对有效。

答案 1 :(得分:1)

我没有看到在这里使用正则表达式的目的,除非你喜欢难以想象的痛苦。如果我必须找到重复的话,我会

  • 获取一系列单词

    var words = "...".split(',');
    
  • 如果您愿意,可以选择小写所有内容

  • 对数组进行排序

    words.sort()
    
  • 重复项现在应该都在数组的连续位置。

作为一个额外的优势,我非常确定这将比正则表达式版本更有效。