[英]Improve my code: Regex parse a comma separated numeric list
This code in LinqPad outputs a string of numbers in the 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<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. 它有效,但是我的主要重点只是使用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: 我正在使用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();
Instead of writing this code in Regex, Why don't you try to use LINQ
? 而不是使用Regex编写此代码,为什么不尝试使用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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.