Tip: Regex.Escape

Mar 4, 2008

A few days ago I received a patch forBlogEngine.NET through CodePlex. In that patch I saw a little piece of code I’ve never seen before, namely Regex.Escape(string). Now, this is nothing new in the .NET framework, I just never come across it before.

It takes care of a trivial issue I have from time to time when dealing with regular expressions. If you pass in a string into a regular expression, you need to make sure some special characters are escaped first. It could be characters such as #, *, ? and $. Instead of replacing all the characters manually you can use the static Escape method instead like so:

string escapedText = Regex.Escape("Some text with special characters #?+^");

Just thought I’d share in case you also missed this method.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Comments (4) -

Davide Espertini
Davide Espertini Italy
3/4/2008 8:18:42 PM #

useful tip Mads! thx ^^

jtentor
jtentor Argentina
3/4/2008 8:20:14 PM #

All days we learn something ...

cxfx
cxfx Australia
3/4/2008 10:36:37 PM #

Great tip Mads, completely missed that one too.

Nebbercracker
Nebbercracker United States
3/5/2008 1:05:16 AM #

Nice one!

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

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