当前位置:  开发笔记 > 编程语言 > 正文

C#preg_replace?

如何解决《C#preg_replace?》经验,为你挑选了1个好方法。



1> FlySwat..:

真正的男人使用正则表达式,但这里有一个扩展方法,如果你需要它可以将它添加到String:

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

你这样使用它:

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

推荐阅读
刘美娥94662
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有