user6048670 user6048670 - 3 months ago 8
C# Question

Regex for positive integers separated by abritrary space

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

Answer

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:

enter image description here

Comments