Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the regular expression to find the last digit in a string?

Tags:

c#

regex

My brain must be frazzled but I can't get this to work and I've very little experience with regular expressions.

I have a string such as "gfdsgfd354gfdgfd55gfdgfdgfs9gfdgsf".

I need a regular expression to find the last digit in the string - in this case the "9".

EDIT

I should have been clearer but, as I say, I'm frazzled.

It's to insert a hyphen character before the final digit. I'm using C# Regex.Replace. Using the idea already suggested by Dave Sexton I tried the following without success:

    private string InsertFinalDigitHyphen(string data)
    {
        return Regex.Replace(data, @"(\d)[^\d]*$", " $1");
    }

With this I can process "ABCDE1FGH" with the intention of getting "ABCDE-1FGH" but I actually get "ABCDE-1".

like image 903
R-C Avatar asked Dec 26 '22 02:12

R-C


1 Answers

I always find regular expressions hard to read, so you could do it in an alternative way with the following LINQ statement:

string str = "gfdsgfd354gfdgfd55gfdgfdgfs9gfdgsf";
var lastDigit = str.Last(char.IsDigit);

Output:

9

To insert a hyphen before this one, you can use LastIndexOf instead of Last and use that index to insert the hyphen at the correct location in the string.

like image 172
L-Four Avatar answered Jan 12 '23 00:01

L-Four