BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Regular Expressions
.NET 1.1+

Regular Expression Substitutions

The twelfth part of the Regular Expressions in .NET tutorial looks at substitutions. These allow elements of an input string to be matched and replaced with alternative text. The replacement pattern can include literal characters and elements from the original match.

Including the Entire Match in a Replacement String

If you wish to include the entire match in the replacement text, you can use the placeholder, "$&". This is useful when you wish to add text before or after the match. For example, the code below looks for times in the input string. The replacement text adds square brackets around those matched times.

string input = "9:00 Start\n"
             + "10:30 Coffee\n"
             + "10:45 Session 2\n"
             + "12:30 Lunch";

string find = @"\d{1,2}:\d{2}";
string replace = "[$&]";

string result = Regex.Replace(input, find, replace);

Console.WriteLine(result);

/* OUTPUT
 
[9:00] Start
[10:30] Coffee
[10:45] Session 2
[12:30] Lunch
            
*/

Including Dollar Signs in a Replacement String

The dollar sign is used for all substitutions. This means that if you wish to include a literal dollar sign in the replacement text, you must escape it. To do so, use two adjacent dollar signs to include a single symbol in the replacement.

The final example adjusts the text from a drinks menu. It finds values that appear to be prices and prefixes them with a dollar sign. The first two dollar symbols in the replace variable generate a single symbol in the result. The third is part of the placeholder that includes the full match in the substitution.

string input = "Tea 1.00\n"
             + "Coffee 1.30\n"
             + "Cappucino 2.15\n"
             + "Latte 2.15";

string find = @"\d+.\d{2}";
string replace = "$$$&";

string result = Regex.Replace(input, find, replace);

Console.WriteLine(result);

/* OUTPUT
 
Tea $1.00
Coffee $1.30
Cappucino $2.15
Latte $2.15
            
*/
23 November 2015