-3

Need regex expression in C# to extract 2 digits from the last but 2 digits.

For example consider the string "QWEREIA89RR". Here I want to extract "89"

Rahul Sundar
  • 462
  • 7
  • 22
  • 5
    It looks like you are looking to create a regex, but do not know where to get started. Please check [Reference - What does this regex mean](https://stackoverflow.com/questions/22937618) resource, it has plenty of hints. Also, refer to [Learning Regular Expressions](https://stackoverflow.com/questions/4736) post for some basic regex info. Once you get some expression ready and still have issues with the solution, please edit the question with the latest details and we'll be glad to help you fix the problem. – Wiktor Stribiżew Feb 04 '21 at 18:52
  • 1
    Also the [regex tag wiki](https://stackoverflow.com/tags/regex/info) contains very useful information, specifically see "How to ask" – Chayim Friedman Feb 05 '21 at 08:54
  • Thanks for references. The answer is (..(?=..$)) – Rahul Sundar Feb 11 '21 at 12:27

2 Answers2

-1

Here is a approach with linq

string input = "Q1WEREIA89RR";
string result = string.Concat(input.Where(char.IsDigit).Reverse().Take(2).Reverse());
fubo
  • 39,783
  • 16
  • 92
  • 127
-1

use the regex ([0-9]+)

using System;
using System.Text.RegularExpressions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "Q1WEREIA89RR";
            var matches = Regex.Matches(input, @"([0-9]+)", RegexOptions.Compiled);
            if (matches.Count>0)
            {
                var all = string.Join("",matches.SelectMany(x => x.Value));
                int numOfChars = 2;
                var last2 = string.Join("", all.Skip(all.Length - numOfChars).Take(numOfChars));
                Console.WriteLine(last2);
            }
            Console.ReadLine();
        }
    }
}
Nitin S
  • 5,628
  • 9
  • 46
  • 85