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: