How to get last 2 characters from string in C# using Regex?

Set the string −

string str = "Cookie and Session";

Use the following Regex to get the last 2 characters from string −

Regex.Match(str,@"(.{2})\s*$")

The following is the code −

Example

using System;
using System.Text.RegularExpressions;
public class Demo {
   public static void Main() {
      string str = "Cookie and Session";
      Console.WriteLine(Regex.Match(str,@"(.{2})\s*$"));
   }
}

Output

on
Updated on: 2026-03-11T22:50:42+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements