www.gibmonks.com

Table of Contents




Previous Page
Next Page

Recipe 10.5. Replacing Characters or Words in a String

Problem

You are given a string in which a complex pattern of characters needs to be replaced with a new string.

Solution

Using the Replace instance method on the Regex class allows for easy replacement of text within a string. The overloaded Replace methods shown in Example 10-5 accept a source string that contains characters or words to be replaced, a matchPattern to match the replaceable text in the source parameter, and a replaceStr string to replace the text matched by matchPattern. In addition two parameters, count and startPos, control the number of replacements allowed and where the replacements start from in the source string, respectively.

Example 10-5. Overloaded Replace methods

using System;
using System.Text.RegularExpressions;

public class RegexUtils
{
    public static string ReplaceStrWithChar(string source, char matchPattern,
                                            string replaceStr)
    {
        return (ReplaceStrWithStr(source, matchPattern.ToString( ),
                                  replaceStr, -1, 0));
    }

    public static string ReplaceStrWithChar(string source, char matchPattern,
                             string replaceStr, int count)
    {
        return (ReplaceStrWithStr(source, matchPattern.ToString( ),
                 replaceStr, count, 0));
    }
    
    public static string ReplaceStrWithChar(string source, char matchPattern,
                             string replaceStr, int count, int startPos)
    {
        return (ReplaceStrWithStr(source, matchPattern.ToString( ),
                 replaceStr, count, startPos));
    }
    
    public static string ReplaceStrWithStr(string source, string matchPattern,
                             string replaceStr)
    {
        return (ReplaceStrWithStr(source, matchPattern, replaceStr, -1, 0));
    }

    public static string ReplaceStrWithStr(string source, string matchPattern,
                             string replaceStr, int count)
    {
        return (ReplaceStrWithStr(source, matchPattern, replaceStr, count, 0));
    }

    public static string ReplaceStrWithStr(string source, string matchPattern,
                             string replaceStr, int count, int startPos)

    {
        Regex RE = new Regex(matchPattern);
        string newString = RE.Replace(source, replaceStr, count, startPos);

        return (newString);
    }
}

To use the overloaded Replace methods to replace the word "FOO" with the word "BAR" in a sentence, you could write the following:

	public static void TestReplace( )
	{
	    string source = "Replace the FOO in this text block of text FOO.";
	    string matchPattern = "FOO";
	    string replaceStr = "BAR";

	    Console.WriteLine(Replace(source, matchPattern, replaceStr));
	    Console.WriteLine(Replace(source, matchPattern, replaceStr, -1));
	    Console.WriteLine(Replace(source, matchPattern, replaceStr, -1, 0));
	    Console.WriteLine(Replace(source, matchPattern, replaceStr, 1));
	    Console.WriteLine(Replace(source, matchPattern, replaceStr, 1, 0));
	    Console.WriteLine(Replace(source, matchPattern, replaceStr, 1));
	    Console.WriteLine(Replace(source, matchPattern, replaceStr, 1, 20));

	    Console.WriteLine(Replace(source, matchPattern, replaceStr, -1, 0));
	    Console.WriteLine(Replace(source, matchPattern, replaceStr, 1, 0));
	    Console.WriteLine(Replace(source, matchPattern, replaceStr, 1, 20));
	}

which would produce the following output:

	Replace the BAR in this text block of text BAR.
	Replace the BAR in this text block of text BAR.
	Replace the BAR in this text block of text BAR.
	Replace the BAR in this text block of text FOO.
	Replace the BAR in this text block of text FOO.
	Replace the BAR in this text block of text FOO.
	Replace the FOO in this text block of text BAR.
	Replace the BAR in this text block of text BAR.
	Replace the BAR in this text block of text FOO.
	Replace the FOO in this text block of text BAR.

This code looks for the word "FOO", and each time this pattern is found, the string "BAR" is substituted for the matched string ("FOO").

Discussion

Using the overloaded instance Replace method on the Regex class, you can easily substitute a string for a pattern in a second string each time that pattern is found. Several overloads of this method provide even more flexibility in determining where to replace matches and how many matches will be replaced.

An overloaded static Replace method is also provided on the Regex class. This method is somewhat different than its instance method counterpart. This static Replace method does not allow for the flexibility of a startPos or a count parameter. In lieu of these parameters, an options parameter is used. This parameter allows for modification of the RegexOptions options. If you require that the regular expression options (RegexOptions) be controllable, rather than using the less flexible static Regex.Replace method, you can modify the overloaded Replace methods as shown in Example 10-6.

Example 10-6. Modifying overloaded Replace methods to accept a RegexOptions parameter

public class RegexUtils
{

    // Constant to provide a default set of options for the regular expression

    const RegexOptions defaultOptions = RegexOptions.IgnorePatternWhitespace |
                                        RegexOptions.Multiline;

    public static string ReplaceStrWithChar(string source, char matchPattern,
                                 string replaceStr)
    {
        return (ReplaceStrWithStr(source, matchPattern.ToString( ), replaceStr, 
-1, 0,

                        defaultOptions));
    }

    public static string ReplaceStrWithChar(string source, char matchPattern,
                                 string replaceStr, int count)
    {
        return (ReplaceStrWithStr(source, matchPattern.ToString( ), replaceStr,
                        count, 0, defaultOptions));
    }

    public static string ReplaceStrWithChar(string source, char matchPattern,
                                 string replaceStr, int count, int startPos)
    {
        return (ReplaceStrWithStr(source, matchPattern.ToString( ), replaceStr,
                        count, startPos, defaultOptions));
    }
    public static string ReplaceStrWithChar(string source, char matchPattern,
                                 string replaceStr, int count, int startPos,
                                 RegexOptions options)

    {
        return (ReplaceStrWithStr(source, matchPattern.ToString( ), replaceStr,
                        count, startPos, options));
    }
    public static string ReplaceStrWithStr(string source, string matchPattern,
                                 string replaceStr)
    {
        return (ReplaceStrWithStr(source, matchPattern, replaceStr, -1, 0,

                        defaultOptions));
    }

    public static string ReplaceStrWithStr(string source, string matchPattern,
                                 string replaceStr, int count)
    {
        return (ReplaceStrWithStr(source, matchPattern, replaceStr, count, 0,

                        defaultOptions));
    }

    public static string ReplaceStrWithStr(string source, string matchPattern,
                                 string replaceStr, int count, int startPos)
    {
        return (ReplaceStrWithStr(source, matchPattern, replaceStr, count,
                                  startPos, defaultOptions));
    }

    public static string ReplaceStrWithStr(string source, string matchPattern,
                                 string replaceStr, int count, int startPos,

                                 RegexOptions options)
    {
        Regex RE = new Regex(matchPattern, options);
        string newString = RE.Replace(source, replaceStr, count, startPos);

        return (newString);
    }
}

An options parameter of type RegexOptions has been added to the end of the last method's parameter list. This Replace method uses this options parameter to define how the Regex object will use the regular expression. Note also that a constant defaultOptions of type RegexOptions has been defined to provide a uniform way to represent the default set of options in each overloaded method.

See Also

See the ".NET Framework Regular Expressions" topic in the MSDN documentation.


Previous Page
Next Page