Example input: " 1 4 2 5 9 "
Wanted: "1"
, "4"
, "2"
, "5"
, "9"
Use like
var rgx = new Regex("???");
var matches = rgx.Matches(" 1 4 2 5 9 ");
var nums = new List<int>();
foreach(var match in matches)
nums.Add(match.Caputre.Value);
Example input: " 1 4 2 5 9 "
Wanted: "1"
, "4"
, "2"
, "5"
, "9"
Use like
var rgx = new Regex("???");
var matches = rgx.Matches(" 1 4 2 5 9 ");
var nums = new List<int>();
foreach(var match in matches)
nums.Add(match.Caputre.Value);
If you are sure there are only spaces and digit chunks, you can use LINQ and parse integers with int.Parse
:
var str = " 1 4 2 5 9 ";
var res = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)
.Select(r => int.Parse(r))
.ToList();
If you also need a kind of a pre-validation (to make sure your string only contains any whitespace and digit chunks, you may use a safer regex based solution:
var res2 = Regex.Matches(str, @"^(?:\s*([0-9]+))+\s*$")
.Cast<Match>()
.SelectMany(p => p.Groups[1].Captures.Cast<Capture>().Select(m => int.Parse(m.Value)))
.ToList();
Both result in:
Split would be a slower way to do it.
Try using matches(), something like:
var nums = new List<int>();
foreach (Match match in Regex.Matches(" 1 4 2 5 9 ", @"\d+"))
{
nums.Add(Int32.Parse(match.Value));
}
///////////////
StringBuilder builder = new StringBuilder();
foreach (int nN in nums)
{
builder.Append(nN).Append(",");
}
string result = builder.ToString();
Console.WriteLine("{0}", result);