You can easily solve this without any regex using string.Split and int.Parse :
var coords = s.Split(',') .Select(x => x.Split('/')) .Select(a => new { X = int.Parse(a[0]), Y = int.Parse(a[1]) });
If you want to use a regular expression to validate a string, you can do it like this:
"^(?!,)(?:(?:^|,)[0-9]+/[0-9]+)*$"
If you want to use the regex approach as well to extract the data, you can first check the string using the regex above and then add the following data:
var coords = Regex.Matches(s, "([0-9]+)/([0-9]+)") .Cast<Match>() .Select(match => new { X = int.Parse(match.Groups[1].Value), Y = int.Parse(match.Groups[2].Value) });
If you really want to test and retrieve data at the same time as one regular expression, you can use two capture groups and find the results in the Captures property for each group. Here, one way you could validate and retrieve data using a single regular expression:
List<Group> groups = Regex.Matches(s, "^(?!,)(?:(?:^|,)([0-9]+)/([0-9]+))*$") .Cast<Match>().First() .Groups.Cast<Group>().Skip(1) .ToList(); var coords = Enumerable.Range(0, groups[0].Captures.Count) .Select(i => new { X = int.Parse(groups[0].Captures[i]), Y = int.Parse(groups[1].Captures[i]) });
However, you might be wondering if the complexity of this solution is compared to a solution based on string.Split .
source share