Computer >> Máy Tính >  >> Lập trình >> C#

Thay thế các phần của một chuỗi bằng C # Regex

Đặt một chuỗi -

string str = "Bit and Bat";

Giả sử bạn cần thay thế bất cứ thứ gì bên trong B và t thành A và viết hoa chuỗi hoàn chỉnh. Để làm được điều đó, hãy sử dụng Replace -

Regex.Replace(str, "B.t", "BAT");

Hãy cho chúng tôi xem mã hoàn chỉnh -

Ví dụ

using System;
using System.Text.RegularExpressions;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         string str = "Bit and Bat";
         Console.WriteLine(str);
         string res = Regex.Replace(str, "B.t", "BAT");
         Console.WriteLine(res);
      }
   }
}

Đầu ra

Bit and Bat
BAT and BAT