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".
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".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With