Get first numbers from String

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


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

string input = "1567438absdg345";

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

The Linq approach:

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

You can loop through the string and test if the current character is numeric via 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
}

Tags:

C#

String

Regex