从字符串中查找并提取数字

本文翻译自: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());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值