TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Regex.Replace Examples: MatchEvaluator

Use Regex.Replace and MatchEvaluator to manipulate strings based on patterns.
Regex.Replace. This method processes text replacements. It handles simple and complex replacements. For complex patterns, we use a MatchEvaluator delegate to encode the logic.DelegatesRegex
To learn how to use Regex.Replace, we change a string with lowercased words to have uppercased ones. But many other replacements can be done.
First example. This program uses the Regex.Replace static method with a string replacement. It is possible to specify a delegate of type MatchEvaluator for more complex replacements.

Pattern: We use a pattern to replace all 3-letter sequences starting and ending with certain letters with a replacement string.

Tip: The Regex method allows you to replace variations in the string in one statement.

Parameters: Regex.Replace is a public static method and we pass it 3 parameters—the input, the pattern and the replacement string data.

Next: The program replaces all parts of the source string that start with N and ending with lowercase t with another 3 letters.

C# program that uses Regex.Replace method using System; using System.Text.RegularExpressions; class Program { static void Main() { // This is the input string we are replacing parts from. string input = "Dot Net Not Perls"; // Use Regex.Replace to replace the pattern in the input. // ... The pattern N.t indicates three letters. // ... N, any character, and t. string output = Regex.Replace(input, "N.t", "NET"); // Write the output. Console.WriteLine(input); Console.WriteLine(output); } } Output Dot Net Not Perls Dot NET NET Perls
MatchEvaluator. We can specify a MatchEvaluator. This is a delegate method that the Regex.Replace method calls to modify the match. Here we use MatchEvaluator to uppercase matches.Uppercase First Letter

String: You can use Regex.Replace for simple replacements by using a string argument. For complex replacements, use MatchEvaluator.

UpperFirst: In Regex.Replace, we use the delegate(Match match) syntax for a method that alters strings to have an uppercase first letter.

Tip: Delegate methods are methods you can use as variables and parameters. They introduce some syntactic complexity.

C# program that capitalizes strings using System; using System.Text.RegularExpressions; class Program { static void Main() { // Input strings. const string s1 = "marcus aurelius"; const string s2 = "the golden bowl"; const string s3 = "Thomas jefferson"; // Write output strings. Console.WriteLine(TextTools.UpperFirst(s1)); Console.WriteLine(TextTools.UpperFirst(s2)); Console.WriteLine(TextTools.UpperFirst(s3)); } } public static class TextTools { /// <summary> /// Uppercase first letters of all words in the string. /// </summary> public static string UpperFirst(string s) { return Regex.Replace(s, @"\b[a-z]\w+", delegate(Match match) { string v = match.ToString(); return char.ToUpper(v[0]) + v.Substring(1); }); } } Output Marcus Aurelius The Golden Bowl Thomas Jefferson
Discussion. The pattern in the Regex.Replace call uses escape sequences. The syntax is described here. The metacharacters match specific patterns (ranges) of text.
Regex pattern description \b Word break: Matches where a word starts. [a-z] Matches any lowercase ASCII letter. We only need to match words with lowercase first letters. This is a character range expression. \w+ Word characters: Matches must have one or more characters.
Other uses. Microsoft indicates we can use MatchEvaluator to perform validation. We can use it "to perform custom verifications or operations at each Replace operation."

Tip: To enhance this capitalization algorithm, you could store a Dictionary of words that need special-casing, such as DeBruijn.

However: This requires a bit of manual work to find most of the names using different rules.

A summary. Regex.Replace can be used in 2 ways. The MatchEvaluator delegate offers a high degree of control. With a string, the Regex.Replace method can be used for simpler tasks.Replace
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf