O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.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 following overloaded Replace methods 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 there are two parameters, count and startPos, to control the number of replacements allowed and where the replacements start from in the source string, respectively:

using System; using System.Text.RegularExpressions; public static string Replace(string source, char matchPattern, string replaceStr) { return (Replace(source, matchPattern.ToString( ), replaceStr, -1, 0)); } public static string Replace(string source, char matchPattern, string replaceStr, int count) { return (Replace(source.ToString( ), matchPattern.ToString( ), replaceStr, count, 0)); } public static string Replace(string source, char matchPattern, string replaceStr, int count, int startPos) { return (Replace(source.ToString( ), matchPattern.ToString( ), replaceStr, count, startPos)); } public static string Replace(string source, string matchPattern, string replaceStr) { return (Replace(source, matchPattern, replaceStr, -1, 0)); } public static string Replace(string source, string matchPattern, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required