Bookmark and Share

Find and Replace Text with Regex

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.

blog comments powered by Disqus

KodefuGuru.GetInfo()

Chris Eargle
LinkedIn Twitter Technorati Facebook

Chris Eargle
Telerik Developer Evangelist, C# MVP

JustCode

Telerik .NET Ninja

 

INETA Community Speakers Program

 

MVP - Visual C#

 

Friend of RedGate

World Map

Tag cloud

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.