user6592730 user6592730 - 1 year ago 65
C# Question

How to get a number in a string?

I want to get a integer value in a string. Any suggessions?

Take this as an example.

768 - Hello World

According to the preceding string i want to get the 768 to a variable. How to do so?

Answer Source
Int32.Parse(Regex.Match(some_string, @"\d+").Value);

some_string represents a variable that is of a string data type. The regex will return the very first number encountered starting from left. In your example it's 768. If the some_string contains 'hello 768", it will still return 768.


If you want to do without using regex, you can do so using a simple loop-

public string GetFirstNumber(string some_string) {

   if (string.IsNullOrEmpty(some_string)) {
        return string.Empty; // You could return null to indicate no data

    StringBuilder sb = new StringBuilder();
    bool found = false;

    foreach(char c in some_string){
            found = true;
        } else if(found){
            // If we have already found a digit, 
            // and current character is not a digit, stop looping

    return sb.ToString();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download