本文翻译自:Find and extract a number from a string
I have a requirement to find and extract a number contained within a string. 我需要查找并提取字符串中包含的数字。
For example, from these strings: 例如,从以下字符串中:
string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
How can I do this? 我怎样才能做到这一点?
#1楼
参考:https://stackoom.com/question/JrYi/从字符串中查找并提取数字
#2楼
Did the reverse of one of the answers to this question: How to remove numbers from string using Regex.Replace? 这个问题的答案之一是否相反: 如何使用Regex.Replace从字符串中删除数字?
// Pull out only the numbers from the string using LINQ
var numbersFromString = new String(input.Where(x => x >= '0' && x <= '9').ToArray());
var numericVal = Int32.Parse(numbersFromString);
#3楼
static string GetdigitFromString(string str)
{
char[] refArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] inputArray = str.ToCharArray();
string ext = string.Empty;
foreach (char item in inputArray)
{
if (refArray.Contains(item))
{
ext += item.ToString();
}
}
return ext;
}
#4楼
Here's a Linq
version: 这是Linq
版本:
string s = "123iuow45ss";
var getNumbers = (from t in s
where char.IsDigit(t)
select t).ToArray();
Console.WriteLine(new string(getNumbers));
#5楼
string verificationCode ="dmdsnjds5344gfgk65585";
string code = "";
Regex r1 = new Regex("\\d+");
Match m1 = r1.Match(verificationCode);
while (m1.Success)
{
code += m1.Value;
m1 = m1.NextMatch();
}
#6楼
这是我清理电话号码以仅获取数字的方法:
string numericPhone = new String(phone.Where(Char.IsDigit).ToArray());