我如何一气呵成执行若干字符串替换? [英] How do I perform several string replacements in one go?
问题描述
我写在C#中的应用程序,它允许用户根据文件名进行数据库查询。
I'm writing an app in C# which allows the user to perform database queries based on file names.
我使用了 Regex.Replace(字符串,MatchEvaluator)
过载进行替代,因为我希望用户能够有替换字符串如 SELECT * FROM表WHERE record_id =修剪($ 1)
尽管我们正在使用不支持像修剪功能(),数据库
I'm using the Regex.Replace(string, MatchEvaluator)
overload to perform replacements, because I want the user to be able to have replacement strings like SELECT * FROM table WHERE record_id = trim($1)
even though the DB we're using doesn't support functions like trim().
我不希望是做了一系列的更新换代,其中,如果$ 1的值包含$ 2,无论是更换发生。我如何一气呵成执行若干字符串替换?我知道PHP的str_replace函数支持数组作为参数;是不是也有类似功能的C#?
What I don't want is to do a series of replacements where if the value of $1 contains "$2", both replacements occur. How do I perform several string replacements in one go? I know PHP's str_replace supports arrays as arguments; is there a similar function for C#?
推荐答案
没有什么内置的,但你可以尝试这样的:
There's nothing built-in, but you could try something like this:
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];
});
}
}
这篇关于我如何一气呵成执行若干字符串替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!