Home   |   QuickStart Welcome   |   ASP.NET   |   Web Services   |   How Do I...?   
  |   I want my samples in...      

How Do I...? Common Tasks QuickStart Tutorial

How Do I...Use Regular Expressions to make replacements?



The Regular Expressions library can often ease the time it takes to generate string replacement functions. By specifying a pattern of strings to be replaced, you do not have to search for every possible variation of a string. Once a Regex object that matches every possible string to be replaced is created, the Replace method can be used to generate a result. The Replace method can be most easily used by passing in the source string and the replacement string. The Replace method will return the results as a String.

		
Regex digitregex = new Regex("(?<digit>[0-9])");
String before = "Here is so4848me te88xt with emb4493edded numbers.";
 ...
String after = digitregex.Replace(before, "");
C#


You can also reuse the matched string in the replacement. In the previous snippet we have a named capture of ?<digit>. This named capture can be reused in the replacement string as ${digit}. Note that ordinal captures can be used as well, $123, which would evaluate to 123 captures in our pattern.

This example illustrates how to use the Replace method of Regex to remove all digits from the input string.

Example

VB RegexReplace.exe
View Source
[This sample can be found at C:\DevFusion.Data\legacy\quickstart.developerfusion.co.uk\QuickStart\howto\samples\RegularExpressions\RegexReplace\]



Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2004 Microsoft Corporation. All rights reserved.