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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9080492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:48:38  来源:igfitidea点击:

Get first numbers from String

c#regexstring

提问by Alaa Osta

How to get the first numbers from a string?

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

Example: I have "1567438absdg345"

示例:我有“1567438absdg345”

I only want to get "1567438" without "absdg345", I want it to be dynamic, get the first occurrence of Alphabet index and remove everything after it.

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

采纳答案by Guffa

You can use the TakeWhileextension methods to get characters from the string as long as they are digits:

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

string input = "1567438absdg345";

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

回答by TJHeuvel

You can loop through the string and test if the current character is numeric via Char.isDigit. ? ? ?

您可以遍历字符串并通过 测试当前字符是否为数字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
}

回答by musefan

forget the regex, create this as a helper function somewhere...

忘记正则表达式,将其创建为某处的辅助函数...

string input = "1567438absdg345";
string result = "";

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

回答by BrokenGlass

The Linq approach:

Linq 方法:

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

回答by f2lollpll

Another approach

另一种方法

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
}

Test:

测试:

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

Result:

结果:

1567438
0

1567438
0

回答by stema

Or the regex approach

或者正则表达式方法

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

^matches the start of the string and \d+the following digits

^匹配字符串的开头和\d+后面的数字

回答by Zafer

An old-fashioned Regular expressionist way:

一种老式的正则表现主义方式:

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;
}

If it cannot parse, the method returns 0.

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

回答by Thit Lwin Oo

Please try this

请试试这个

string val = "1567438absdg345";

System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("[1-9][0-9]*");

string valNum = reg.Match(val).Value;

回答by Sgedda

This way you get the first digit from the string.

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

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;

Another alternative that should do it:

应该这样做的另一种选择:

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

I dont know why I got an empty string as a result in the numbers list above though?

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

Solved it like below, but seems a like the regex should be improved to do it immediately.

像下面那样解决它,但似乎应该改进正则表达式以立即执行。

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