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!
This one will reject extraneous commas at the start or end of the line, if that's important to you.
Replace
possible|value|patterns
with a regex that matches your allowed values.In JavaScript, use
split
to help out, and catch any negative digits as well:You might want to specify language just to be safe, but
ought to work
I had a slightly different requirement, to parse an encoded dictionary/hashtable with escaped commas, like this:
I think this is an elegant solution, with a trick that avoids a lot of regex complexity:
I think it can be adapted to the original question with an expression like
@"([0-9]+),\s?"
and parse onGroups[0]
.I hope it's helpful to somebody and thanks for the tips on getting it close to there, especially Asaph!
I suggest you to do in the following way:
which would work for a list containing 1 or more elements.
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.