从字符串中获取第一个数字

本文关键字:第一个 数字 获取 字符串 | 更新日期: 2023-09-27 18:21:55

如何从字符串中获取第一个数字?

示例:我有"1567438absdg345"

我只想得到没有"absdg345"的"1567438",我希望它是动态的,得到字母表索引的第一次出现,并删除它之后的所有内容。

从字符串中获取第一个数字

您可以使用TakeWhile扩展方法从字符串中获取字符,只要它们是数字:

string input = "1567438absdg345";
string digits = new String(input.TakeWhile(Char.IsDigit).ToArray());

Linq方法:

string input = "1567438absdg345";
string output = new string(input.TakeWhile(char.IsDigit).ToArray());

或者regex方法

String s = "1567438absdg345";
String result = Regex.Match(s, @"^'d+").ToString();

^匹配字符串的开头,'d+匹配以下数字

您可以循环遍历字符串,并通过Char.isDigit测试当前字符是否为数字。

string str = "1567438absdg345";
string result = "";
for (int i = 0; i < str.Length; i++) // loop over the complete input
{
    if (Char.IsDigit(str[i])) //check if the current char is digit
        result += str[i];
    else
        break; //Stop the loop after the first character
}

忘记正则表达式,在某个地方创建它作为辅助函数。。。

string input = "1567438absdg345";
string result = "";
foreach(char c in input)
{
   if(!Char.IsDigit(c))
   {
      break;
   }
   result += c;
}

的另一种方法

private int GetFirstNum(string inp)
{
    string final = "0"; //if there's nothing, it'll return 0
    foreach (char c in inp) //loop the string
    {
        try
        {
            Convert.ToInt32(c.ToString()); //if it can convert
            final += c.ToString(); //add to final string
        }
        catch (FormatException) //if NaN
        {
            break; //break out of loop
        }
    }
    return Convert.ToInt32(final); //return the int
}

测试:

    Response.Write(GetFirstNum("1567438absdg345") + "<br/>");
    Response.Write(GetFirstNum("a1567438absdg345") + "<br/>");

结果:

1567438
0

一种老式的常规表现主义方式:

public long ParseInt(string str)
{
    long val = 0;
    System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"^(['d]+).*$");
    System.Text.RegularExpressions.Match match = reg.Match(str);
    if (match != null) long.TryParse(match.Groups[1].Value, out val);
    return val;
}

如果无法解析,则该方法返回0。

请尝试此

string val = "1567438absdg345";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[1-9][0-9]*");
string valNum = reg.Match(val).Value;

这样可以从字符串中获得第一个数字。

string stringResult = "";
bool digitFound = false;
foreach (var res in stringToTest)
{
    if (digitFound && !Char.IsDigit(res))
        break;
    if (Char.IsDigit(res))
    {
        stringResult += res;
        digitFound = true;
    }
}
int? firstDigitInString = digitFound ? Convert.ToInt32(stringResult) : (int?)null;

另一个应该做的选择:

string[] numbers = Regex.Split(input, @"'D+");

我不知道为什么我在上面的数字列表中得到了一个空字符串?

像下面这样解决了它,但似乎regex应该改进以立即完成。

string[] numbers = Regex.Split(firstResult, @"'D+").Where(x => x != "").ToArray();

我知道这个问题已经有10年的历史了,但只是为了防止其他人遇到它。只有当数字位于输入字符串的开头时,接受的答案才会给你第一个数字。

当字符串以数字以外的任何字符开头时,它将返回一个空字符串。在使用接受的答案之前,您首先需要知道第一个数字的索引并生成子字符串。

string input = "abc123def456ghi";
string digits = null;
if (!string.IsNullOrEmpty(input))
{
    var indexFirstDigit = input.IndexOfAny("0123456789".ToCharArray());
    if (indexFirstDigit >= 0)
    {
        digits = new String(input.Substring(indexFirstDigit).TakeWhile(Char.IsDigit).ToArray());
    }
}

尽管使用正则表达式需要更少的行

string input = "abc012def345ghi";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[''d]+");
string digits = reg.Match(input).Value;