C# 不重新声明字符串的正则表达式替换

C# 不重新声明字符串的正则表达式替换,c#,C#,我现在正在做一系列类似这样的正则表达式替换 _skeleton = Regex.Replace(_skeleton, "&%currTIME", DateTime.Now.ToString()); 有没有办法让我不用写“_skeleton=” 可能使用“out”?如果您不想在同一个字符串上重复多次替换,可以将调用嵌套到Regex.Replace(): (编辑答案,因为我的回复太长,无法发表评论) 您甚至不需要缩进它们: _skeleton = Regex.Replace(Regex.

我现在正在做一系列类似这样的正则表达式替换

_skeleton = Regex.Replace(_skeleton, "&%currTIME", DateTime.Now.ToString());
有没有办法让我不用写“_skeleton=”


可能使用“out”?

如果您不想在同一个字符串上重复多次替换,可以将调用嵌套到
Regex.Replace()


(编辑答案,因为我的回复太长,无法发表评论)

您甚至不需要缩进它们:

_skeleton = Regex.Replace(Regex.Replace(Regex.Replace/*...*/(_skeleton,
            "foo", "bar"),
            "baz", "blaz"),
            //..
            "TIMTOWTDI", "There Is More Than One Way To Do It"
            ));

由于字符串是不可变的,因此不能更改其内容。您必须创建一个包含所需内容的新字符串

将其视为任何其他不可变类型(DateTime、int等)

您可以将功能包装为更具功能性:

public void MyRegexReplace(ref string mystring, string pattern, string replaceWith)
{
    mystring = Regex.Replace(mystring, pattern, replaceWith);
}
然后像这样称呼它:

MyRegexReplace(ref _skeleton, "&%currTIME", DateTime.Now.ToString());
但这对我来说似乎没什么用处。

如何定义:

 void static void RexReplace(ref strTarget, string searchPatter, string replacePattern)
 {
      str = Regex.Replace(str, searchPatter, replacePattern); 
 }
然后写

 RexReplace(ref _skeleton, "&%currTIME", DateTime.Now.ToString());

不幸的是,我有大约20次替换。如果不写新行,它是不可读的。@cam:我已经在原始答案中对您的评论做出了回应,因为评论框太难看了。只需使用
mystring
作为ref参数:/
 void static void RexReplace(ref strTarget, string searchPatter, string replacePattern)
 {
      str = Regex.Replace(str, searchPatter, replacePattern); 
 }
 RexReplace(ref _skeleton, "&%currTIME", DateTime.Now.ToString());