如何一次性执行多个字符串替换?

我正在用C#编写一个应用程序,允许用户根据文件名执行数据库查询。

我正在使用Regex.Replace(string, MatchEvaluator)重载来执行替换,因为我希望用户能够拥有替换字符串,如SELECT * FROM table WHERE record_id = trim($1)即使我们正在使用的数据库不支持trim()等函数。

我不想要的是进行一系列替换,如果$ 1的值包含“$ 2”,则两个替换都会发生。 如何一次性执行多个字符串替换? 我知道PHP的str_replace支持数组作为参数; C#有类似的function吗?

内置任何东西,但你可以尝试这样的事情:

 string foo = "the fish is swimming in the dish"; string bar = foo.ReplaceAll( new[] { "fish", "is", "swimming", "in", "dish" }, new[] { "dog", "lies", "sleeping", "on", "log" }); Console.WriteLine(bar); // the dog lies sleeping on the log // ... public static class StringExtensions { public static string ReplaceAll( this string source, string[] oldValues, string[] newValues) { // error checking etc removed for brevity string pattern = string.Join("|", oldValues.Select(Regex.Escape).ToArray()); return Regex.Replace(source, pattern, m => { int index = Array.IndexOf(oldValues, m.Value); return newValues[index]; }); } } 

你最好的方法是遍历一个字符串数组并在每次迭代期间调用Replace,一般来说这就是其他函数在幕后的function。

更好的方法是创建自己的方法,就像PHP的str_replace工作方式一样。

请参阅下面的示例,您也可以根据具体需要进行更改

 // newValue - Could be an array, or even Dictionary for both strToReplace/newValue private static string MyStrReplace(string strToCheck, string[] strToReplace, string newValue) { foreach (string s in strToReplace) { strToCheck = strToCheck.Replace(s, newValue); } return strToCheck; } 

我认为循环模式和替换arrays是最好的选择。 即使str_replace也有你所描述的问题。

 echo str_replace(array("a", "b", "c"), array("b", "c", "d"), "abc"); result: "ddd"