C# Find and Replace Text with Regex

C#

Public Domain

Find and Replace Text with Regex

Download (right click, save as, rename as appropriate)

Embed

Tags:

c# regex replace
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
//A common scenario you may be faced with is displaying text to a user that contains identifying information such as social security numbers. This is a pretty simple task in .NET if you know the //correct class and methods to use.

//The first thing you’re going to need is a regular expression pattern. Here’s a simple one for a social security number: \d{3}-\d{2}-\d{4}.

//The next thing you should do is add a reference to System.Text.RegularExpressions. Now, we can get to coding.

string text = "garbage text 123-12-1234 more garbage";
string pattern = @"\d{3}-\d{2}-\d{4}";
text = Regex.Replace(text, pattern, m => 
                    "***-**-" + m.Value.Substring(m.Value.Length - 4, 4));

//Regex.Replace existed before the Func classes, so it requests MatchEvaluator rather than Func<Match, string>. No matter, we can still use a lambda here.

//This was a pretty simple solution to a common problem. Enjoy.