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

时间:2010-08-13 20:54:02

标签: c# linq string c#-4.0 linq-to-objects

是否可以编写一个查询,我们可以从任何给定的字符串中获取所有可以解析为int的字符?

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

结果必须为"67231"

甚至更轻微一点:我们只能得到前三个数字吗?

7 个答案:

答案 0 :(得分:22)

这将为您提供字符串

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

前3个字符在.Take(3)

之前使用ToArray()

答案 1 :(得分:11)

以下情况应该有效。

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视为单个数字序列,或2个不同的数字。我上面的解决方案假设您希望最终结果为672

答案 2 :(得分:3)

public static string DigitsOnly(string strRawData)
  {
     return Regex.Replace(strRawData, "[^0-9]", "");
  }

答案 3 :(得分:2)

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

答案 4 :(得分:1)

这样的事情怎么样?

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

答案 5 :(得分:0)

正则表达式:

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

答案 6 :(得分:0)

> '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 . . .