C# preg_replace?

前端 未结 5 1522
猫巷女王i
猫巷女王i 2020-12-10 09:46

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 somet

5条回答
  •  有刺的猬
    2020-12-10 09:51

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

提交回复
热议问题