User987 User987 - 1 year ago 55
ASP.NET (C#) Question

Taking out the last characther from the string, storing it into the variable and then deleting it using Regex C#

I have a string like following (for example):

Testing stackoverflow 6
Testing stackoverflow 67
Testing stackoverflow 687
Testing stackoverflow 6789

Now I know for a fact that every time the string is gonna end up with a number value. I need to take out this number... It can be a number anywhere in between 1 to 5000... I figured that using lambda expressions wouldn't help since I can't really determine how big will the number be, so I figured regex might be a good way to solve this, but how ?


When I take out the number from regex and storing it like this:

int somevalue = Convert.ToInt32(whatever regex takes out);
// Now I have to remove the number from the string...

Anyone has any clue?

Answer Source
var match = Regex.Match(myString, @"\d+$");
if(match != null) {
    long ret;
    long.TryParse(match.Groups[0].Value, out ret);
    myString = Regex.Replace(myString, @"\d+$", "");

The regex match only if there is a number at the end of the string and declaring ret as long permit you to cover the case where ret is longer than int.MaxValue

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download