Using LINQ to parse the numbers from a string

前端 未结 7 1481
忘掉有多难
忘掉有多难 2021-02-19 22:00

Is it possible to write a query where we get all those characters that could be parsed into int from any given string?

For example we have a string like: \"$%^DDFG

7条回答
  •  清歌不尽
    2021-02-19 22:37

    Regex:

    private int ParseInput(string input)
    {
        System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"\d+");
        string valueString = string.Empty;
        foreach (System.Text.RegularExpressions.Match match in r.Matches(input))
            valueString += match.Value;
        return Convert.ToInt32(valueString);
    }
    

    And even slight harder: Can we get only first three numbers?

        private static int ParseInput(string input, int take)
        {
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"\d+");
            string valueString = string.Empty;
            foreach (System.Text.RegularExpressions.Match match in r.Matches(input))
                valueString += match.Value;
            valueString = valueString.Substring(0, Math.Min(valueString.Length, take));
            return Convert.ToInt32(valueString);
        }
    

提交回复
热议问题