代码之家  ›  专栏  ›  技术社区  ›  iLemming

使用LINQ解析字符串中的数字

  •  9
  • iLemming  · 技术社区  · 14 年前

    例如,我们有一个字符串,如: "$%^DDFG 6 7 23 1"

    "67231"

    更难的是:我们只能得到前三个数字吗?

    7 回复  |  直到 14 年前
        1
  •  24
  •   Carlos Muñoz Boom    14 年前

    这会给你你的线

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

    对于前3个字符的使用 .Take(3) 之前 ToArray()

        2
  •  11
  •   Alan    14 年前

    var myString = "$%^DDFG 6 7 23 1";
    
    //note that this is still an IEnumerable object and will need
    // conversion to int, or whatever type you want.
    var myNumber = myString.Where(a=>char.IsNumber(a)).Take(3);
    

    不清楚你想不想 23 被认为是一个数字序列,或两个不同的数字。我上面的解决方案假设您希望最终结果是 672

        3
  •  3
  •   THines01    14 年前
    public static string DigitsOnly(string strRawData)
      {
         return Regex.Replace(strRawData, "[^0-9]", "");
      }
    
        4
  •  2
  •   Kelsey    14 年前
    string testString = "$%^DDFG 6 7 23 1";
    string cleaned = new string(testString.ToCharArray()
        .Where(c => char.IsNumber(c)).Take(3).ToArray());
    

    如果要使用白名单(不总是数字):

    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());
    
        5
  •  1
  •   Matthew Whited    14 年前

    像这样的怎么样?

    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); 
    
        6
  •  0
  •   Jake    14 年前

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

    更难的是:我们能不能

        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);
        }
    
        7
  •  0
  •   Murxiii Javed    11 年前
    > '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 . . .