Regex for Comma delimited list

2019-01-03 09:34发布

What is the regular expression to validate a comma delimited list like this one:

12365, 45236, 458, 1, 99996332, ......

标签: regex csv
10条回答
beautiful°
2楼-- · 2019-01-03 10:12

This one will reject extraneous commas at the start or end of the line, if that's important to you.

((, )?(^)?(possible|value|patterns))*

Replace possible|value|patterns with a regex that matches your allowed values.

查看更多
\"骚年 ilove
3楼-- · 2019-01-03 10:12

In JavaScript, use split to help out, and catch any negative digits as well:

'-1,2,-3'.match(/(-?\d+)(,\s*-?\d+)*/)[0].split(',');
// ["-1", "2", "-3"]
// may need trimming if digits are space-separated
查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-03 10:16

You might want to specify language just to be safe, but

(\d+, ?)+(\d+)?

ought to work

查看更多
劳资没心,怎么记你
5楼-- · 2019-01-03 10:16

I had a slightly different requirement, to parse an encoded dictionary/hashtable with escaped commas, like this:

"1=This is something, 2=This is something,,with an escaped comma, 3=This is something else"

I think this is an elegant solution, with a trick that avoids a lot of regex complexity:

if (string.IsNullOrEmpty(encodedValues))
{
    return null;
}
else
{
    var retVal = new Dictionary<int, string>();
    var reFields = new Regex(@"([0-9]+)\=(([A-Za-z0-9\s]|(,,))+),");
    foreach (Match match in reFields.Matches(encodedValues + ","))
    {
        var id = match.Groups[1].Value;
        var value = match.Groups[2].Value;
        retVal[int.Parse(id)] = value.Replace(",,", ",");
    }
    return retVal;
}

I think it can be adapted to the original question with an expression like @"([0-9]+),\s?" and parse on Groups[0].

I hope it's helpful to somebody and thanks for the tips on getting it close to there, especially Asaph!

查看更多
We Are One
6楼-- · 2019-01-03 10:17

I suggest you to do in the following way:

(\d+)(,\s*\d+)*

which would work for a list containing 1 or more elements.

查看更多
Emotional °昔
7楼-- · 2019-01-03 10:19

This regex extracts an element from a comma separated list, regardless of contents:

(.+?)(?:,|$)

If you just replace the comma with something else, it should work for any delimiter.

查看更多
登录 后发表回答