Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีดึงตัวอักษร 2 ตัวสุดท้ายจากสตริงใน C# ด้วย Regex


กำหนดสตริง:

string str = "Cookie and Session";

ใช้ Regex รูปแบบนี้เพื่อดึง 2 ตัวอักษรสุดท้าย:

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

โค้ดตัวอย่างเต็ม

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*$"));
    }
}

ผลลัพธ์

on

คำอธิบาย Regex:

  • (.{2}) - จับกลุ่ม (capture group) 2 ตัวอักษรใดๆ
  • \s* - อาจจะมี whitespace 0 หรือหลายตัว
  • $ - จบสตริง

หมายเหตุ: บทความนี้เป็นเรื่อง C# ไม่ใช่ C++