Javascript 改进正则表达式以匹配列表中的重复项
我使用正则表达式在列表中查找重复项。这只是一个简短的逗号分隔列表,性能不是问题,所以没有必要告诉我,出于这些原因,我不应该使用正则表达式Javascript 改进正则表达式以匹配列表中的重复项,javascript,regex,Javascript,Regex,我使用正则表达式在列表中查找重复项。这只是一个简短的逗号分隔列表,性能不是问题,所以没有必要告诉我,出于这些原因,我不应该使用正则表达式 // returns a match because some is repeated "some,thing,here,some,whatever".match(/(^|,)(.+?)(,|,.+,)\2(,|$)/g) 问题。。。 这个正则表达式可以改进吗 它是否涵盖了逗号不在单独字符串中的所有可能情况 有没有更好(最好是可读性更好、效率更高)的方法 如
// returns a match because some is repeated
"some,thing,here,some,whatever".match(/(^|,)(.+?)(,|,.+,)\2(,|$)/g)
问题。。。
如果我想在逗号分隔的列表中查找DUP,我会这样做,使用对象的哈希功能累积唯一值并检测DUP:
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);
函数getDups(列表){
var数据=list.split(“,”);
var uniques={},dups={},item,uniqueList=[];
对于(变量i=0;i这种类型的实现可以很好地扩展到大量的字,因为dup检测相对有效。我看不出在这里使用正则表达式的目的,除非你喜欢难以想象的痛苦。如果我必须找到重复的,我会的
- 获取一组单词
var words = "...".split(',');
- 如果您愿意,可以选择将所有内容小写
- 对数组进行排序
words.sort()
- 现在,重复项应全部位于阵列的连续位置
作为一个额外的优势,我很确定这将比正则表达式版本更有效。可能只使用不需要捕获任何内容的非捕获组:
/(?:^ |),(.+?)(?:,|,.+,)\1(?:,|$)/
有趣的是,您可以使用一个非常简单的正则表达式来查找彼此相邻的副本。。。所以“string,of,things.split(',).sort().join(',).match(/(^ |,).+?,\1(,|$)/)
同样,我不确定它是否会比regex更高效,我认为它在性能方面有着不应有的声誉。它实际上执行得相当好,因为一旦找到无法返回匹配项的路径,它就会立即切断。我希望看到这两种方法的基准测试。。。事实上,我认为我可以这样做。好吧,你的方法大约快了10倍——正如你从这把小提琴上看到的:你打算如何找到重复的?通过在数组中循环并与后面的元素进行比较,这是基本思想——不过jfriend的哈希表方法应该更简单。至于效率,我们分割数组的方法大约是O(N)或O(NlogN),而带有反向引用的复杂正则表达式通常需要指数时间!