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

时间:2012-05-01 13:53:04

标签: c# regex

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

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

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

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

取代

例如,如果输入" ahfbsdrts stb"    输出将是" ahaaadrta ata"

3 个答案:

答案 0 :(得分:0)

为什么不使用对String.Replace的多次调用?

答案 1 :(得分:0)

试试这个:

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);                             
 }
}

答案 2 :(得分:0)

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

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

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

这样的东西