使用正则表达式删除逗号分隔列表中的重复项? [英] Removing duplicates in a comma-separated list with a regex?

查看:181
本文介绍了使用正则表达式删除逗号分隔列表中的重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何使用正则表达式过滤掉字符串中的重复项,其中字符串以逗号分隔。我想在javascript中执行此操作,但我已经开始考虑如何使用反向引用。

I'm trying to figure out how to filter out duplicates in a string with a regular expression, where the string is comma separated. I'd like to do this in javascript, but I'm getting caught up with how to use the back-references.

例如:

1,1,1,2,2,3,3,3,3,4,4,4,5

成为:

1,2,3,4,5

或者:

a,b,b,said,said, t, u, ugly, ugly

成为

a,b,said,t,u,ugly


推荐答案

为什么在javascript代码中使用正则表达式?这是示例代码(虽然凌乱):

Why use regex when you can do it in javascript code? Here is sample code (messy though):

var input = 'a,b,b,said,said, t, u, ugly, ugly';
var splitted = input.split(',');
var collector = {};
for (i = 0; i < splitted.length; i++) {
   key = splitted[i].replace(/^\s*/, "").replace(/\s*$/, "");
   collector[key] = true;
}
var out = [];
for (var key in collector) {
   out.push(key);
}
var output = out.join(','); // output will be 'a,b,said,t,u,ugly'

p / s :for循环中的一个正则表达式是修剪标记,而不是使它们唯一

p/s: that one regex in the for-loop is to trim the tokens, not to make them unique

这篇关于使用正则表达式删除逗号分隔列表中的重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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