views:

60

answers:

2

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#?

A: 

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;
}
Xander
That has the problem I want to avoid - the first time through the loop can put a value in that gets replaced again the next time through. In your example it's not so bad because you only have one new value, but I want an array of new values too.
Simon
+1  A: 

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];
            });
    }
}
LukeH