使用 C# 正則表示式替換字串中的部分


設定字串 −

string str = "Bit and Bat";

假設你需要將 B 和 t 之間的所有內容替換為 A 並大寫整個字串。為此,請使用 Replace -

Regex.Replace(str, "B.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);
         string res = Regex.Replace(str, "B.t", "BAT");
         Console.WriteLine(res);
      }
   }
}

輸出

Bit and Bat
BAT and BAT

更新時間: 22-6 月-2020

2K+ 瀏覽

助力你的事業

完成課程獲得認證

開始
廣告
© . All rights reserved.