如何使用正则表达式替换 C# 中的字符串的一部分

本文关键字:字符串 一部分 何使用 正则表达式 替换 | 更新日期: 2023-09-27 18:32:52

我在 C# 和正则表达式方面几乎没有经验,但我需要尝试这个逻辑:

 string replacedText = Regex.Replace(
     "ssdf bonnets sdf sdf sdf ", 
     @"(?i)^(.+ )?(bonnet)(s?)( .+)?$", 
     "$1hood$3$4"
 );

上面的代码是对stackoverflow中问题的答案:

更换一部分绳子,同时保持其余部分完好无损?而不是只检测单词(引擎盖),我想替换多个值,例如,如果它找到"f"或"b"或"s",它将被替换为"a"?

例如,如果输入"ahfbsdrts stb" 输出 WLL 为 "Ahaaadrta ATA"

如何使用正则表达式替换 C# 中的字符串的一部分

我发布了另一个短代码选项。

请参阅 http://forums.asp.net/t/1185961.aspx/1

类似string temp = Regex.Replace(input, @"[fbs]", "a");

为什么不直接使用对 String.Rereplace 的多次调用?

试试这个:

using System;
using System.Text.RegularExpressions;
public class Example
{
 public static void Main()
 {
  string input = "ssdf bonnets sdf sdf sdf ";
  string pattern_1 = "f";
  string replacement = "a";
  Regex rgx_1 = new Regex(pattern_1);
  string result = rgx_1.Replace(input, replacement);
  string pattern_2 = "b";
  Regex rgx_2 = new Regex(pattern_2);
  result = rgx_2.Replace(result, replacement);
  string pattern_3 = "s";
  Regex rgx_3 = new Regex(pattern_3);
  result = rgx_3.Replace(result, replacement);
  Console.WriteLine("Original String: {0}", input);
  Console.WriteLine("Replacement String: {0}", result);                             
 }
}