Best option how to find last 2 digits in string with RegEx or LINQ in C#?

Viewed 1267

I am trying to get the last 2 digits in a string with RegEx or LINQ. For example I got these strings:

N43OET28W -> result should be 28
N1OET86W  -> result should be 86
S02CT55A  -> result should be 55
M4AKT99A  -> result should be 99
1W24ET39W -> result should be 39
S03KT45A  -> result should be 45
M1AKT23A  -> result should be 23
N1OET35W  -> result should be 35
N12FET42W -> result should be 42
MAKTFDAAD -> result should be null or 0
N3XUK407Q -> result should be 07
MAKT23A   -> result should be 23

For now I tried this code:

  getIntPattern("N1WET99W");
  getIntPattern("S03KT45A");
  getIntPattern("M1AKT23A");
  getIntPattern("N1OET35W");
  getIntPattern("N1OET42W");
  getIntPattern("MAKTFDAAD");
  getIntPattern("N12FET42W");

  private int getIntPattern(string text)
  {
    int result = 0;
    string m = Regex.Matches(text, @".*?\d+.*?(\d+)")
               .Cast<Match>()
               .Select(match => match.Groups[1].Value).First();
    int.TryParse(m, out result);
    return result;
  }

Is there a better way to achieve this? The input string doesn't have the same length, and can contain more digits at the beginning. I only need the last two digits.

6 Answers
Related