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
C# RegexReplace.exe
[This sample can be found at M:\web\users\Sites\AspnetQuickStart\v2.0\QuickStart\howto\samples\RegularExpressions\RegexReplace\
To build this sample, open the SDK command prompt and navigate to the above path. Build the sample using the build tool msbuild
passing the solution file as the first parameter: msbuild mySample.sln. The compiled executable will be found in the sub directory \bin
directory.]
Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2005 Microsoft Corporation. All rights reserved.
|