我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
当前回答
获取字符串中包含的所有正数的扩展方法:
public static List<long> Numbers(this string str)
{
var nums = new List<long>();
var start = -1;
for (int i = 0; i < str.Length; i++)
{
if (start < 0 && Char.IsDigit(str[i]))
{
start = i;
}
else if (start >= 0 && !Char.IsDigit(str[i]))
{
nums.Add(long.Parse(str.Substring(start, i - start)));
start = -1;
}
}
if (start >= 0)
nums.Add(long.Parse(str.Substring(start, str.Length - start)));
return nums;
}
如果你也想要负数,只需修改这段代码来处理负号(-)
假设输入如下:
"I was born in 1989, 27 years ago from now (2016)"
得到的数字列表将是:
[1989, 27, 2016]
其他回答
这个问题并没有明确地说明您只是想要字符0到9,但从您的示例集和注释中相信这是正确的并不过分。这是做这个的代码。
string digitsOnly = String.Empty;
foreach (char c in s)
{
// Do not use IsDigit as it will include more than the characters 0 through to 9
if (c >= '0' && c <= '9') digitsOnly += c;
}
为什么不想使用Char.IsDigit()——数字包括分数、下标、上标、罗马数字、货币分子、围起来的数字和特定于脚本的数字。
只需使用一个RegEx来匹配字符串,然后转换:
Match match = Regex.Match(test , @"(\d+)");
if (match.Success) {
return int.Parse(match.Groups[1].Value);
}
对于那些想要十进制数字的字符串与Regex在两行:
decimal result = 0;
decimal.TryParse(Regex.Match(s, @"\d+").Value, out result);
同样的事情也适用于float, long等等…
Ahmad Mageed在这里提供了一种有趣的方法,使用Regex和StringBuilder以它们在字符串中出现的顺序提取整数。
一个使用Regex的例子。根据艾哈迈德·马吉德的帖子,下文如下:
var dateText = "MARCH-14-Tue";
string splitPattern = @"[^\d]";
string[] result = Regex.Split(dateText, splitPattern);
var finalresult = string.Join("", result.Where(e => !String.IsNullOrEmpty(e)));
int DayDateInt = 0;
int.TryParse(finalresult, out DayDateInt);
string s = "kg g L000145.50\r\n";
char theCharacter = '.';
var getNumbers = (from t in s
where char.IsDigit(t) || t.Equals(theCharacter)
select t).ToArray();
var _str = string.Empty;
foreach (var item in getNumbers)
{
_str += item.ToString();
}
double _dou = Convert.ToDouble(_str);
MessageBox.Show(_dou.ToString("#,##0.00"));