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

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

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

结果必须是"67231"

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

这会给你你的字符串

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

并且对于前3个字符使用。在ToArray()之前使用.Take(3) ToArray()

以下应该有效。

 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

 public static string DigitsOnly(string strRawData) { return Regex.Replace(strRawData, "[^0-9]", ""); } 
 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()); 

这样的事怎么样?

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

正则表达式:

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