使用 C# 正则表达式替换字符串的部分内容

csharpprogrammingserver side programming更新于 2025/9/1 8:52:17

设置字符串 −

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

相关文章