简体   繁体   English

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

[英]How to use Regular expressions to replace a part of string in C#?

I have little experince in C# and regex, but I need try this this logic: 我对C#和正则表达式的经验很少,但是我需要尝试以下逻辑:

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

The above code was an answer to question in stackoverflow: 上面的代码是stackoverflow中问题的答案:

Replacing a part of string while keeping the rest intact? 在保留其余部分不变的同时替换字符串的一部分? instead of detecting just the word (bonnet) I want to replace multiple values for example if it finds "f" or "b" or "s" it will be replaced by "a"? 而不是仅检测单词(帽子),我想替换多个值,例如,如果找到“ f”或“ b”或“ s”,它将替换为“ a”吗?

for example if the input "ahfbsdrts stb" the output wll be "ahaaadrta ata" 例如,如果输入“ ahfbsdrts stb”,则输出将为“ ahaaadrta ata”

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

Try this: 尝试这个:

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

I post another option for short code. 我发布了另一个简短代码选项。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM