Reputation: 21162
This code in LinqPad outputs a string of numbers in the Regex:
void Main()
{
string a = "1, 2, 3, 4, 5, 6, 7";
var myList = Regex.Match(a, @"^\s*((\d+)\s*,?\s*)+\s*$")
.Groups[2].Captures.ToList();
myList.Dump();
}
public static class EM
{
public static List<string> ToList( this CaptureCollection value)
{
var result = new List<string>();
foreach( var item in value)
{
result.Add( ((Capture) item).Value );
}
return result;
}
}
It works but my main focus is simply to put only the numbers in a string array using the Regex. Is there something short and sweet to accomplish the same thing?
Edit:
I'm using Regex because I need to parse something like this:
string a = "deptid = 1, 2, 3, 4, 5, 6, 7";
var myList = Regex.Match(a,
@"^\s*(?<field>[A-Za-z0-9]+)\s*(?<op>==?)\s*((\d+)\s*,?\s*)+\s*$")
.Groups[2].Captures.ToList();
Upvotes: 1
Views: 363
Reputation: 1640
Instead of writing this code in Regex, Why don't you try to use LINQ
?
try this one:
List<string> yourList = a.Split(',').Select(sValue => sValue.Trim()).ToList();
But if you want to stick with array, then use this:
var yourList = a.Split(',').Select(sValue => sValue.Trim()).ToArray();
Upvotes: 8