Find and Replace Text with Regex

by KodefuGuru 12. January 2010 17:18

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.

Tags:

Kodefu

Comments

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen

Whois KodefuGuru

Chris Eargle

Chris Eargle
.NET Community Champion

LinkedIn Twitter Technorati Facebook

MVP - Visual C#

 

INETA Community Champions
Friend of RedGate
Telerik .NET Ninja
Community blogs & blog posts

I am a #52er


World Map

RecentComments

Comment RSS

Tag cloud

Disclaimer

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

© Copyright 2010