December 2007
Intermediate to advanced
896 pages
19h 57m
English
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.
Use the overloaded instance Replace method shown in Example 10-5 that accepts a MatchEvaluator delegate along with its other parameters. The MatchEvaluator delegate is a callback method that overrides the default behavior of the Replace method.
Example 10-5. Overloaded Replace method that accepts a MatchEvaluator delegate
using System; using System.Text.RegularExpressions; public static string MatchHandler(Match theMatch) { // Handle all ControlID_ entries. if (theMatch.Value.StartsWith("ControlID_", StringComparison.Ordinal)) { long controlValue = 0; // Obtain the numeric value of the Top attribute. Match topAttribiteMatch = Regex.Match(theMatch.Value, "Top=([-]*\\d*)"); if (topAttribiteMatch.Success) { if (topAttribiteMatch.Groups[1].Value.Trim().Equals("")) { // If blank, set to zero. return (theMatch.Value.Replace( topAttribiteMatch.Groups[0].Value.Trim(), "Top=0")); } else if (topAttribiteMatch.Groups[1].Value.Trim().StartsWith("-" , StringComparison.Ordinal)) { // If only a negative sign (syntax error), set to zero. return (theMatch.Value.Replace( topAttribiteMatch.Groups[0].Value.Trim(), "Top=0")); } else { // We have a valid number. // Convert the matched string to a numeric value. ...Read now
Unlock full access