Tip: Regex.Escape

by Mads Kristensen 5. March 2008 04:31

A few days ago I received a patch for BlogEngine.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

Tags:

Tips and tricks

Comments

3/5/2008 5:18:42 AM #

Davide Espertini

useful tip Mads! thx ^^

Davide Espertini Italy |

3/5/2008 5:20:14 AM #

jtentor

All days we learn something ...

jtentor Argentina |

3/5/2008 7:36:37 AM #

cxfx

Great tip Mads, completely missed that one too.

cxfx Australia |

3/5/2008 10:05:16 AM #

Nebbercracker

Nice one!

Nebbercracker United States |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

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

© Copyright 2008