Removing duplicates in a comma-separated list with a regex?

前端 未结 5 1524
滥情空心
滥情空心 2020-12-18 07:45

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\

5条回答
  •  情话喂你
    2020-12-18 08:08

    If you insist on RegExp, here's an example in Javascript:

    "1,1,1,2,2,3,3,3,3,4,4,4,5".replace (
        /(^|,)([^,]+)(?:,\2)+(,|$)/ig, 
        function ($0, $1, $2, $3) 
        { 
            return $1 + $2 + $3; 
        }
    );
    

    To handle trimming of whitespace, modify slightly:

    "1,1,1,2,2,3,3,3,3,4,4,4,5".replace (
        /(^|,)\s*([^,]+)\s*(?:,\s*\2)+\s*(,|$)\s*/ig, 
        function ($0, $1, $2, $3) 
        { 
            return $1 + $2 + $3; 
        }
    );
    

    That said, it seems better to tokenise via split and handle duplicates.

提交回复
热议问题