2017-04-22 8 views
0

我想用占位符替换字符串中的所有字符串文字。例如,如果我有以下字符串:使用正则表达式替换C#中的字符串文字

string s1 =“foo”;字符串s2 =“bar”;字符串s3 =“baz”;

我想与替换此:

字符串S1 =#0#;字符串s2 =#1#;字符串s2 =#2#;

并且还在数据结构中保留替换的字符串文字{“foo”,“bar”,“baz”}以供以后使用。

我可以通过蛮力丑陋的编码来做到这一点。但是,我想知道是否有一个使用正则表达式来完成此操作的好方法?

我的尝试是:

MatchCollection textConstants = Regex.Matches(text, "\".*\""); 
for (int i=0; i < textConstants.Count; i++) 
{ 
    text=text.Replace(textConstants[i].Value, "#" + i + "#"); 
}' 

这似乎不是很漂亮

+1

是否已进行了在使用正则表达式的尝试?如果您努力解决问题并解释卡住的位置,人们可以帮助您解决问题,而不仅仅是提供解决方案。 – 4castle

回答

1

现在你有两个问题:

var s = "string s1 = \"foo\"; string s2 = \"bar\"; string s3 = \"baz\";"; 

var list = new List<string>(); 

var result = Regex.Replace(s, "\".*?\"", m => { list.Add(m.Value); 
               return "#" + (list.Count - 1) + "#"; }); 
+0

谢谢。这是我期待的答案 –

+0

[It is not correct](http://regexstorm.net/tester?p=%22.*%3f%22&i=string+s1+%3d+%22%5c%22foo%5c %22%22%3b),因为字符串文字可能包含转义序列。 –