Regular expression match all numbers after the last dash?

c#, regex

Solution

Sure, the simplest solution would be something like this:

(\d+)[^-]*$

This will match one or more digits, captured in group 1, followed by zero or more of any character other than a hyphen, followed by the end of the string. In other words, it will match any sequence of digits as long as there are no hyphens between that sequence and the end of the string. You then just have to extract group 1 from the match. For example:

var inputs = new[] {
    "test-123-2-456",
    "123-test",
    "123-test-456",
    "123-test-456sdfsdf",
    "123-test-asd456"
};
foreach(var str in inputs)
{
    var m = Regex.Match(str, @"(\d+)[^-]*$");
    Console.WriteLine("{0} --> {1}", str, m.Groups[1].Value);
}

Produces:

test-123-2-456 --> 456
123-test --> 
123-test-456 --> 456
123-test-456sdfsdf --> 456
123-test-asd456 --> 456

Alternatively, if you could use a negative lookahead like this:

\d+(?!.*-)

This will match one or more digit characters so long as they are not followed by a hyphen. Only the digits will be included in the match.

Note that these two options behave differently if there are two or more sets of numbers after the last `-`, e.g. `foo-123bar456`. In this case it's not entirely clear what you want to happen, but the first pattern will simply match everything starting from the first sequence of digits to the end (`123bar456`) with group 1 only containing the first sequence of digits (`123`). If you'd like to change this so that it only captures the last sequence of digits, place a `\d` inside the character class (i.e. `(\d+)[^\d-]*$`). The second second pattern would produce a separate match for each sequence digits (in this example, `123` and `456`) but the `Regex.Match` method will only give you the first match.

Problem

Trying to find the last instance of numbers after last dash in a string so `test-123-2-456` would return `456` `123-test` would return `""` `123-test-456` would return `456` `123-test-456sdfsdf` would return `456` `123-test-asd456` would return `456` The expression, `@"[^-]*$"`, does not match the numbers though, and I have tried using [\d] but to no avail.

Original source