我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
我需要找到并提取字符串中包含的数字。
例如,从这些字符串:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
我该怎么做呢?
当前回答
使用StringBuilder比在循环中连接字符串的性能稍好一些。如果处理的是大字符串,它的性能要高得多。
public static string getOnlyNumbers(string input)
{
StringBuilder stringBuilder = new StringBuilder(input.Length);
for (int i = 0; i < input.Length; i++)
if (input[i] >= '0' && input[i] <= '9')
stringBuilder.Append(input[i]);
return stringBuilder.ToString();
}
注意:上面的例子函数只适用于正数
其他回答
只需使用一个RegEx来匹配字符串,然后转换:
Match match = Regex.Match(test , @"(\d+)");
if (match.Success) {
return int.Parse(match.Groups[1].Value);
}
下面是另一种Linq方法,它从字符串中提取第一个数字。
string input = "123 foo 456";
int result = 0;
bool success = int.TryParse(new string(input
.SkipWhile(x => !char.IsDigit(x))
.TakeWhile(x => char.IsDigit(x))
.ToArray()), out result);
例子:
string input = "123 foo 456"; // 123
string input = "foo 456"; // 456
string input = "123 foo"; // 123
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);
\d+是整数的正则表达式。所以
//System.Text.RegularExpressions.Regex
resultString = Regex.Match(subjectString, @"\d+").Value;
返回subjectString中第一个数字出现的字符串。
Int32.Parse(resultString)会给你一个数字。
如果数字有小数点,可以使用下面的方法
using System;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
Console.WriteLine(Regex.Match("anything 876.8 anything", @"\d+\.*\d*").Value);
Console.WriteLine(Regex.Match("anything 876 anything", @"\d+\.*\d*").Value);
Console.WriteLine(Regex.Match("$876435", @"\d+\.*\d*").Value);
Console.WriteLine(Regex.Match("$876.435", @"\d+\.*\d*").Value);
}
}
}
结果:
"anything 876.8 anything" ==> 876.8 "anything 876 anything" ==> 876 "$876435" ==> 876435 "$876.435" ==> 876.435
示例:https://dotnetfiddle.net/IrtqVt