Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

8.6. Augmenting the Basic String Replacement Function

Problem

You need to replace character patterns within the target string with a new string. However, in this case, each replacement operation has a unique set of conditions that must be satisfied in order to allow the replacement to occur. Consider, for example, that you receive a string in the form of XML (or possibly HTML). You wish to modify an attribute of a specific XML tag to a particular number, but only if that number is within a specified range (or possibly outside of a particular range).

Solution

Use the overloaded instance Replace method that accepts a MatchEvaluator delegate along with its other parameters. The MatchEvaluator delegate, which is a callback method that overrides the default behavior of the Replace method, is shown here:

using System; using System.Text.RegularExpressions; public static string MatchHandler(Match theMatch) { // Handle Top property of the Property tag if (theMatch.Value.StartsWith("<Property")) { long topPropertyValue = 0; // Obtain the numeric value of the Top property Match topPropertyMatch = Regex.Match(theMatch.Value, "Top=\"([-]*\\d*)"); if (topPropertyMatch.Success) { if (topPropertyMatch.Groups[1].Value.Trim( ).Equals("")) { // If blank, set to zero return (theMatch.Value.Replace("Top=\"\"", "Top=\"0\"")); } else if (topPropertyMatch.Groups[1].Value.Trim( ).Equals("-")) { // If only a negative sign (syntax error), set to zero return (theMatch.Value.Replace("Top=\"-\"", "Top=\"0\"")); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata