ใช้ Regex.Replace แทนที่ส่วนท้ายที่ต้องการลบด้วยสตริงว่าง ("")
ตัวอย่าง: ลบเครื่องหมาย ! ท้ายสตริง
using System;
using System.Text.RegularExpressions;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
string s1 = "Demo Text!";
string s2 = Regex.Replace(s1, "!", "");
Console.WriteLine("\"{0}\"\n\"{1}\"", s1, s2);
}
}
}
ผลลัพธ์
"Demo Text!" "Demo Text"
แนะนำ: สำหรับการลบตัวอักษรเฉพาะตัว ใช้ String.TrimEnd(chars) หรือ StringBuilder จะเร็วกว่าและอ่านง่ายกว่า Regex