Regex.Replace vs String.Replace

In C# newsgroup I used to see the question on “how to replace string?”. Someone gives the String.Replace solution but other may use Regex.Replace. There are somehow behaving differently.

Try to run this sample that I extended it from the original MSDN sample and see what is happening.

// This code example demonstrates the System.Text.Regular-
// Expressions.Regex.Replace(String, String) method.
 
using System;
using System.Text.RegularExpressions;
 
class Sample
{
  public static void Main()
  {
    // Create a regular expression that matches a series of one
    // or more white spaces.
    string pattern = @"s+";
    Regex rgx = new Regex(pattern);
 
    // Declare a string consisting of text and white spaces.
    string inputStr = "a   b   c   d";
 
    // Replace runs of white space in the input string with a
    // comma and a blank.
    string outputStr = rgx.Replace(inputStr, ", ");
 
    // Display the resulting string.
    Console.WriteLine("Pattern:       "{0}"", pattern);
    Console.WriteLine("Input string:  "{0}"", inputStr);
    Console.WriteLine("Output string: "{0}"", outputStr);
 
    inputStr = "a   b   c   d";
    outputStr = inputStr.Replace(pattern,", ");
    // Display the resulting string.
    Console.WriteLine("Pattern:       "{0}"", pattern);
    Console.WriteLine("Input string:  "{0}"", inputStr);
    Console.WriteLine("Output string: "{0}"", outputStr);
 
    pattern = "   ";
    rgx = new Regex(pattern);
    inputStr = "a   b   c   d";
    outputStr = rgx.Replace(inputStr, ", ");
    // Display the resulting string.
    Console.WriteLine("Pattern:       "{0}"", pattern);
    Console.WriteLine("Input string:  "{0}"", inputStr);
    Console.WriteLine("Output string: "{0}"", outputStr);
 
    inputStr = "a   b   c   d";
    outputStr = inputStr.Replace(pattern, ", ");
    // Display the resulting string.
    Console.WriteLine("Pattern:       "{0}"", pattern);
    Console.WriteLine("Input string:  "{0}"", inputStr);
    Console.WriteLine("Output string: "{0}"", outputStr);
  }
}

 For additional resources:

About these ads

About chanmingman

Ming Man is a senior manager for a development company. With 20 years of experience in the IT field, he has developed system using Clipper, COBOL, VB5, VB6, VB.NET, Java and C #. He is familiar with the N-Tier design of business application and is also an expert with database experience in MS SQL, Oracle and AS 400.
This entry was posted in .Net. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s