从String中获取第一个数字

Ala*_*sta 19 c# regex string

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

示例:我有"1567438absdg345"

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

Guf*_*ffa 35

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

string input = "1567438absdg345";

string digits = new String(input.TakeWhile(Char.IsDigit).ToArray());
Run Code Online (Sandbox Code Playgroud)

  • @MonsterMMORPG:从问题中我可以看出,在这种情况下,期望的结果将是一个空字符串,这就是它返回的内容. (2认同)

Bro*_*ass 19

Linq方法:

string input = "1567438absdg345";
string output = new string(input.TakeWhile(char.IsDigit).ToArray());
Run Code Online (Sandbox Code Playgroud)

  • 删除了我的答案,赞成这个.美丽! (3认同)

ste*_*ema 8

或正则表达式方法

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

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


TJH*_*vel 7

您可以遍历字符串并测试当前字符是否为数字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
}
Run Code Online (Sandbox Code Playgroud)


mus*_*fan 5

忘记正则表达式,在某个地方将其创建为辅助函数...

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

foreach(char c in input)
{
   if(!Char.IsDigit(c))
   {
      break;
   }
   result += c;
}
Run Code Online (Sandbox Code Playgroud)