C# preg_replace

.net.net-2.0c++preg-replace

What is the PHP preg_replace in C#?

I have an array of string that I would like to replace by an other array of string. Here is an example in PHP. How can I do something like that in C# without using .Replace("old","new").

$patterns[0] = '/=C0/';
$patterns[1] = '/=E9/';
$patterns[2] = '/=C9/';


$replacements[0] = 'à';
$replacements[1] = 'é';
$replacements[2] = 'é';
return preg_replace($patterns, $replacements, $text);

Best Solution

Real men use regular expressions, but here is an extension method that adds it to String if you wanted it:

public static class ExtensionMethods
{
    public static String PregReplace(this String input, string[] pattern, string[] replacements)
    {
        if (replacements.Length != pattern.Length)
            throw new ArgumentException("Replacement and Pattern Arrays must be balanced");

        for (var i = 0; i < pattern.Length; i++)
        {
            input = Regex.Replace(input, pattern[i], replacements[i]);                
        }

        return input;
    }
}

You use it like this:

 class Program
    {
        static void Main(string[] args)
        {
            String[] pattern = new String[4];
            String[] replacement = new String[4];

            pattern[0] = "Quick";
            pattern[1] = "Fox";
            pattern[2] = "Jumped";
            pattern[3] = "Lazy";

            replacement[0] = "Slow";            
            replacement[1] = "Turtle";
            replacement[2] = "Crawled";
            replacement[3] = "Dead";

            String DemoText = "The Quick Brown Fox Jumped Over the Lazy Dog";

            Console.WriteLine(DemoText.PregReplace(pattern, replacement));
        }        
    }