C# 改进我的代码:Regex解析逗号分隔的数字列表

C# 改进我的代码:Regex解析逗号分隔的数字列表,c#,regex,C#,Regex,LinqPad中的此代码在正则表达式中输出一个数字字符串: 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

LinqPad中的此代码在正则表达式中输出一个数字字符串:

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;
    }
}
void Main()
{
字符串a=“1,2,3,4,5,6,7”;
var myList=Regex.Match(a,@“^\s*((\d+)\s*,?\s*)+\s*$”)
.Groups[2]。Captures.ToList();
myList.Dump();
}
公共静态类EM
{
公共静态列表ToList(此CaptureCollection值)
{
var result=新列表();
foreach(价值中的var项目)
{
结果.添加((捕获)项).Value);
}
返回结果;
}
}
它可以工作,但我主要关注的是使用正则表达式仅将数字放入字符串数组中。有什么短而甜的东西可以完成同样的事情吗

编辑:

我使用正则表达式是因为我需要解析如下内容:

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();
string a=“deptid=1,2,3,4,5,6,7”;
var myList=Regex.Match(a,
@“^\s*(?[A-Za-z0-9]+)\s*(?==?)\s*((\d+)\s*,?\s*)+\s*$”)
.Groups[2]。Captures.ToList();

与其在Regex中编写此代码,不如尝试使用
LINQ

试试这个:

List<string> yourList = a.Split(',').Select(sValue => sValue.Trim()).ToList();

与其在正则表达式中编写此代码,不如尝试使用
LINQ

试试这个:

List<string> yourList = a.Split(',').Select(sValue => sValue.Trim()).ToList();

对编辑的回应:然后在
=
上使用
Split
,然后在
上使用
Split
之后使用@Timothy Shields所说的+1。您可以显示一些示例xml文本吗?对编辑的回应:然后在
=
上使用
Split
,然后在
上使用
Split
之后。+1与@Timothy Shields所说的一致。您能展示一些示例xml文本吗?