Using LINQ to parse the numbers from a string

前端 未结 7 1479
忘掉有多难
忘掉有多难 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:31

    This will give you your string

    string result = new String("y0urstr1ngW1thNumb3rs".
        Where(x => Char.IsDigit(x)).ToArray());
    

    And for the first 3 chars use .Take(3) before ToArray()

    0 讨论(0)
  • 2021-02-19 22:33
    string testString = "$%^DDFG 6 7 23 1";
    string cleaned = new string(testString.ToCharArray()
        .Where(c => char.IsNumber(c)).Take(3).ToArray());
    

    If you want to use a white list (not always numbers):

    char[] acceptedChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    string cleaned = new string(testString.ToCharArray()
        .Where(c => acceptedChars.Contains(c)).Take(3).ToArray());
    
    0 讨论(0)
  • 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);
        }
    
    0 讨论(0)
  • 2021-02-19 22:39

    How about something like this?

    var yourstring = "$%^DDFG 6 7 23 1";  
    var selected = yourstring.ToCharArray().Where(c=> c >= '0' && c <= '9').Take(3);
    var reduced = yourstring.Where(char.IsDigit).Take(3); 
    
    0 讨论(0)
  • 2021-02-19 22:40
    > 'string strRawData="12#$%33fgrt$%$5"; 
    > string[] arr=Regex.Split(strRawData,"[^0-9]"); int a1 = 0; 
    > foreach (string value in arr) { Console.WriteLine("line no."+a1+" ="+value); a1++; }'
    
    Output:line no.0 =12
    line no.1 =
    line no.2 =
    line no.3 =33
    line no.4 =
    line no.5 =
    line no.6 =
    line no.7 =
    line no.8 =
    line no.9 =
    line no.10 =5
    Press any key to continue . . .
    
    0 讨论(0)
  • 2021-02-19 22:43
    public static string DigitsOnly(string strRawData)
      {
         return Regex.Replace(strRawData, "[^0-9]", "");
      }
    
    0 讨论(0)
提交回复
热议问题