2010-02-24 30 views
0

目前,我正在做一堆的正则表达式替换这样正则表达式替换字符串没有重新说明

_skeleton = Regex.Replace(_skeleton, "&%currTIME", DateTime.Now.ToString()); 

有没有什么办法让它所以我没有写“_skeleton =”?

也许使用'out'?

回答

2

由于字符串是不可变的,所以不能更改它们的内容。你必须用你想要的内容创建一个新的字符串。

认为它像任何其他不变类型(日期时间,整型,等等)

int i = 1; 
i++; // i = i + 1 
i += 2; // i = i + 2 

DateTime d = DateTime.Now 
d = d.AddDays(1); 

string s = "s"; 
s = s + "tring"; 

你可以用的功能是一个小的性质更多的功能:

public void MyRegexReplace(ref string mystring, string pattern, string replaceWith) 
{ 
    mystring = Regex.Replace(mystring, pattern, replaceWith); 
} 

然后这样称呼它:

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

但这对我来说似乎没有用。

+0

只需使用'mystring'作为参数:/ – 2010-02-24 21:51:29

+0

是的。只是编辑来做到这一点。忘记了一秒钟。 – Joel 2010-02-24 21:52:42

0

如果你不希望有继续相同的字符串重复自己多替换,你可以嵌套调用Regex.Replace()

_skeleton = Regex.Replace(
        Regex.Replace(_skeleton, "foo", "bar"), 
      "&%currTIME", DateTime.Now.ToString()); 

(编辑答案,因为我的反应是太长的评论)

你并不需要甚至缩进他们:

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

不幸的是,我有一个20项内容替换。如果不写一个新的话,这是不可读的。 – cam 2010-02-24 21:45:17

+0

@cam:我在原始答案中已经回复了您的评论,因为评论框对此太过尴尬。 – 2010-02-24 21:52:02

0

如何界定:

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

,然后写

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