C# 如果在一行中替换,则用指示替换字符串

C# 如果在一行中替换,则用指示替换字符串,c#,string,replace,C#,String,Replace,我正在寻找一个高效的,有创意的字符串替换。如果使用Regex,我不想调用Regex.IsMatch,然后调用Regex.Replace,因为这不需要通过输入进行两次搜索,而不是一次搜索。我可以执行以下操作,但这同样需要一个额外的局部变量。有没有一种方法可以在没有局部变量的情况下在一行中完成?类似于Regex.TryReplace(ref string input,…)的东西会返回bool string input = "string with pattern"; string replaced

我正在寻找一个高效的,有创意的字符串替换。如果使用Regex,我不想调用
Regex.IsMatch
,然后调用
Regex.Replace
,因为这不需要通过输入进行两次搜索,而不是一次搜索。我可以执行以下操作,但这同样需要一个额外的局部变量。有没有一种方法可以在没有局部变量的情况下在一行中完成?类似于
Regex.TryReplace(ref string input,…)
的东西会返回bool

string input = "string with pattern";
string replaced = Regex.Replace(input , Regex.Escape("pattern"), "replace value", RegexOptions.IgnoreCase);
if (!ReferenceEquals(replaced, input))
{
   input = replaced;
   // do something
}

您可以使用Replace(String,String,String,RegexOptions,TimeSpan)`重载进行try/catch操作

  try {

     Console.WriteLine(Regex.Replace(words, pattern, evaluator, 
                                     RegexOptions.IgnorePatternWhitespace,
                                     TimeSpan.FromSeconds(.25)));      
  }
  catch (RegexMatchTimeoutException) {
     Console.WriteLine("Returned words:");
  }
}


但您仍在执行两个操作:尝试替换和检查是否已替换,这是您一直在执行的操作。我很清楚为什么要在一条线上做两次手术。

这和我的问题有什么关系?