I'm writing an app in C# which allows the user to perform database queries based on file names.
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().
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];
});
}
}
Your best best is to loop through an array of strings and call Replace during each iteration, generally speaking that is what other functions will do under the hood.
Even better would be to create your own method that does just that, similar to how PHP's str_replace works.
See example below, alternatively you can vary it depending on your specific needs
// newValue - Could be an array, or even Dictionary<string, string> 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;
}
I think looping over arrays of patterns and replacements is the best option. Even str_replace has the issue you were describing.
echo str_replace(array("a", "b", "c"), array("b", "c", "d"), "abc");
result: "ddd"