Skip to main content
 首页 » 编程设计

c#之改进我的代码:正则表达式解析逗号分隔的数字列表

2024年01月22日29傻小

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; 
    } 
} 


它有效,但我的主要重点只是使用Regex仅将数字放在字符串数组中。完成同一件事是否有短暂而甜蜜的东西?

编辑:

我正在使用Regex,因为我需要解析以下内容:

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(); 

请您参考如下方法:

而不是使用Regex编写此代码,为什么不尝试使用LINQ?

试试这个:

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


但是,如果要坚持使用数组,请使用以下命令:

var yourList = a.Split(',').Select(sValue => sValue.Trim()).ToArray();