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, ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.