Parse an integer from a string with trailing garbage
.net, c#, parsing
Solution
foreach (var m in Regex.Matches(" 3 - .x. 4", @"\d+"))
{
Console.WriteLine(m);
}
Updated per comments
Not sure why you don't like regular expressions, so I'll just post what I think is the shortest solution.
To get first int:
Match match = Regex.Match(" 3 - .x. - 4", @"\d+");
if (match.Success)
Console.WriteLine(int.Parse(match.Value));
Problem
I need to parse a decimal integer that appears at the start of a string. There may be trailing garbage following the decimal number. This needs to be ignored (even if it contains other numbers.) e.g. ``` "1" => 1 " 42 " => 42 " 3 -.X.-" => 3 " 2 3 4 5" => 2 ``` Is there a built-in method in the .NET framework to do this? `int.TryParse()` is not suitable. It allows trailing spaces but not other trailing characters. It would be quite easy to implement this but I would prefer to use the standard method if it exists.