ใช้ Regex.Replace(input, pattern, replacement) เพื่อค้นหาและแทนที่ส่วนของสตริงที่ตรงกับ Regular Expression
ตัวอย่าง: แทนที่ "B.t" (B ตามด้วยตัวอักษรใดๆ 1 ตัว แล้วตามด้วย t) ด้วย "BAT"
using System;
using System.Text.RegularExpressions;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
string str = "Bit and Bat";
Console.WriteLine(str); // Bit and Bat
string res = Regex.Replace(str, "B.t", "BAT");
Console.WriteLine(res); // BAT and BAT
}
}
}
ผลลัพธ์
Bit and Bat BAT and BAT
Pattern "B.t": . (Dot) หมายถึงตัวอักษรใดๆ 1 ตัว (ยกเว้น Newline) ดังนั้น "Bit" และ "Bat" ตรงตามเงื่อนไข