在字符串中查找整数值

时间:2012-11-12 11:30:59

标签: c#

我希望在以下字符串中找到整数值:

“值=” 5412304756756756756756792114343986"

我怎样才能使用C#?

5 个答案:

答案 0 :(得分:4)

您可以使用正则表达式查找字符串中的数字:

var resultString = Regex.Match(subjectString, @"\d+").Value;

对于负值:

var resultString = Regex.Match(yourString, @"(|-)\d+").Value;

答案 1 :(得分:2)

你可以寻找等号......

string yourString = "value=5412304756756756756756792114343986";
string integerPart = yourString.Split('=')[1];

答案 2 :(得分:2)

您可以使用char.IsDigi t 像。的东西。

string str = "value=5412304756756756756756792114343986";
List<char> justDigits = new List<char>();
foreach(char c in str)
{
    if (char.IsDigit(c))
        justDigits.Add(c);
}

string intValues = new string(justDigits.ToArray());

更短的版本

string intValues = new string(str.Where(char.IsDigit).ToArray());

答案 3 :(得分:2)

您可以使用Regex

int IntVal = Int32.Parse(Regex.Match(yourString, @"(|-)\d+").Value);

这也会匹配负数。您还可以迭代字符串中的每个字符并检查ID是否为数字但不是真正理想的解决方案,因为它可能是瓶颈。

编辑:输入的数字大于长。对于这样的数字,您可以使用BigInteger,从框架4.0开始

答案 4 :(得分:1)

        Match match = new Regex("[0-9]+").Match("value=\"5412304756756756756756792114343986\"");
        while(match.Success)
        {
            // Do something
            match = match.NextMatch();
        }