Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

.net - C# 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...