C# – Get trailing number from string

Veröffentlicht von

A small code snippet how to get the trailing number from a string.

For example Test1 returns 1, Test1245 returns 1245. If no trailing number is found, it returns null.

/// <summary>
/// Gets the trailing number from string, for example "Test 1904" returns 1904
/// "Test" returns null
/// </summary>
/// <param name="foo">the string</param>
/// <returns></returns>
public static int? GetTrailingNumberFromString(string foo)
{
    string sValue = null;

    for (var i = foo.Length - 1; i >= 0; i--)
    {
        var regex = new Regex(@"^\d$");

        if (regex.IsMatch(foo[i].ToString()))
            sValue = foo[i] + sValue;
        else
            break;
    }

    if (sValue != null)
        return Convert.ToInt32(sValue);
    
    return null;
}

Kommentar hinterlassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.