Get the first numbers from a string

I want to get the first instance of numbers in a string.

So I got this input string which could be one of the following:

1: "Event: 1 - Some event"
2: "Event 12 -"
3: "Event: 123"
4: "Event: 12 - Some event 3"

The output of the input string must be:

1: 1
2: 12
3: 123
4: 12

I've tried the following methods but none of them gives me exactly what I want.

number = new String(input.ToCharArray().Where(c => Char.IsDigit(c)).ToArray());
//This gives me all the numbers in the string

var index = input.IndexOfAny("0123456789".ToCharArray());
string substring = input.Substring(index, 4);
number = new string(substring.TakeWhile(char.IsDigit).ToArray());
//This gives me first number and then the numbers in the next 4 characters. However it breaks if there is less than 4 characters after the first number.

EDIT: A lot of people posted good solutions but I ended up accepting the one I actually used in my code. I wish I could accept more answers!

Jon Skeet
people
quotationmark

It seems to me that you just need a regular expression:

using System;
using System.Text.RegularExpressions;

public class Test
{
    static void Main()
    {
        ExtractFirstNumber("Event: 1 - Some event");
        ExtractFirstNumber("Event: 12 -");
        ExtractFirstNumber("Event: 123");
        ExtractFirstNumber("Event: 12 - Some event 3");
        ExtractFirstNumber("Event without a number");
    }

    private static readonly Regex regex = new Regex(@"\d+");
    static void ExtractFirstNumber(string text)
    {
        var match = regex.Match(text);
        Console.WriteLine(match.Success ? match.Value : "No match");
    }
}

The first match will only start at the first digit, and will stop at the first non-digit (or the end of the string). You can use the Length and Index properties of the match to work out where it was within the string if you need to.

people

See more on this question at Stackoverflow