C# 使用C逐个替换字符串中的单词

C# 使用C逐个替换字符串中的单词,c#,regex,string,C#,Regex,String,我试图用C替换字符串中的单词。每次,我都希望替换一个匹配的单词 例如: 这是示例1,这是示例2,这是示例3 让我们逐个替换is,然后我们应该得到3个字符串: 预期结果: 这个例子1,这是例子2,那是例子3。 这是示例1,这是示例2,这是示例3。 这是示例1,这是示例2,这是示例3。 ====更新===== 我是堆栈溢出的新手,谢谢大家的帮助 我正在搜索匹配集合,但不知道如何替换某个索引中的单词匹配索引,所以我问了这个问题。感谢Dmitry提供Linq解决方案并修改此问题的描述!同时感谢Anu为您

我试图用C替换字符串中的单词。每次,我都希望替换一个匹配的单词

例如:

这是示例1,这是示例2,这是示例3

让我们逐个替换is,然后我们应该得到3个字符串:

预期结果:

这个例子1,这是例子2,那是例子3。 这是示例1,这是示例2,这是示例3。 这是示例1,这是示例2,这是示例3。 ====更新=====

我是堆栈溢出的新手,谢谢大家的帮助


我正在搜索匹配集合,但不知道如何替换某个索引中的单词匹配索引,所以我问了这个问题。感谢Dmitry提供Linq解决方案并修改此问题的描述!同时感谢Anu为您提供的解决方案

试试这样的方法:

using System;

class MainClass {
  public static void Main (string[] args) {
      String str = "This is example 1, this is example 2, that is example 3.";
      while(str.Contains("is") ) {
        str.Replace("is", "###")
        Console.WriteLine (str);
      }
  }
}
此代码一直运行,直到字符串不再包含is字符串,每次迭代它都会替换一个并输出当前字符串。

您可以使用Regex和

您可以借助Linq查询源字符串,同时借助正则表达式匹配感兴趣的整个单词:

结果:

This ### example 1, this is example 2, that is example 3
This is example 1, this ### example 2, that is example 3
This is example 1, this is example 2, that ### example 3

到目前为止你试过什么?在此发布代码提示:使用正则表达式,您将拥有一个匹配集合。我是stackoverflow和C的新手。是的,我正在搜索匹配集合,谢谢您的提示。1。str.Replaceis,替换第一次迭代2中的所有内容。str.Replaceis的返回值需要指定为somewhereTrue。我们可以使用此处描述的函数:或此处:来执行此操作对不起,什么是matches.Dump;,求你了?@DmitryBychenko对不起,我是从Linqpad试的。忘了把它取下来。现已更新答案:
This ### example 1, this is example 2, that is example 3. 
This is example 1, this ### example 2, that is example 3. 
This is example 1, this is example 2, that ### example 3 
using System.Linq;
using System.Text.RegularExpressions;

...

string source =
  @"This is example 1, this is example 2, that is example 3";

string word = "is";

string[] result = Regex
  .Matches(source, $@"\b{Regex.Escape(word)}\b", RegexOptions.IgnoreCase)
  .Cast<Match>()
  .Select(match => 
     $"{source.Substring(0, match.Index)}###{source.Substring(match.Index + match.Length)}")
  .ToArray();
Console.Write(string.Join(Environment.NewLine, result));
This ### example 1, this is example 2, that is example 3
This is example 1, this ### example 2, that is example 3
This is example 1, this is example 2, that ### example 3