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


i trying last 2 digits in string regex or linq. example got these strings:

n43oet28w -> result should 28 n1oet86w  -> result should 86 s02ct55a  -> result should 55 m4akt99a  -> result should 99 1w24et39w -> result should 39 s03kt45a  -> result should 45 m1akt23a  -> result should 23 n1oet35w  -> result should 35 n12fet42w -> result should 42 maktfdaad -> result should null or 0 n3xuk407q -> result should 07 makt23a   -> result should 23 

for tried 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 better way achieve this? input string doesn't have same length, , can contain more digits @ beginning. need last 2 digits.

you can try linq: try each 2-letter substring starting string's end:

  string source = "n43oet28w";    string result = enumerable     .range(2, source.length - 1)     .select(index => source.substring(source.length - index, 2))     .where(item => item.all(c => char.isdigit(c)))     .firstordefault(); 

if looking speed, say, have many items analyze suggest for loop:

  int result = -1;   int last = -1;    (int = source.length - 1; >= 0; --i) {     int current = source[i] - '0';      if (current >= 0 && current <= 9)       if (last >= 0 && last <= 9) {         result = current * 10 + last;          break;       }       else         last = current;     else       last = -1;   } 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -