.NET (295) administrative (41) Ajax (42) AngularJS (2) ASP.NET (144) bicycle (2) books (180) browser (8) C# (133) cars (1) chess (28) CodePlex (10) Coma (8) database (47) deployment (3) Entity Framework (2) essay (111) flash/shockwave (2) flex (1) food (3) friend (2) game (20) idea (5) IIS (8) javascript (82) LInQ (2) Linux (6) management (4) manga (42) misc (671) mobile (1) movies (91) MsAccess (1) murder (2) music (64) mysql (1) news (99) permanent (1) personal (68) PHP (1) physics (2) picture (307) places (12) politics (13) programming (503) rant (120) religion (3) science (43) Sharepoint (3) software (58) space (1) T4 (2) technology (11) Test Driven Development (4) translation (2) VB (2) video (97) Visual Studio (44) web design (46) Windows API (8) Windows Forms (3) Windows Server (5) WPF/Silverlight (63) XML (11)

Saturday, May 05, 2007

Escaping Regex replace patterns

When one wants to replace a text, say, case insensitive, one uses the .NET Regex class. In order to make sure the text to be replaced is not interpreted as a Regex pattern, the Regex.Escape method is used. But what about the replacement string? What if you want to replace the text with "${0}", which in Regexian means "the entire matched string" ? You need to somehow escape the replace pattern.

I have no idea where to find this information on MSDN, although I am sure it is hidden somewhere in all that Regex labyrinth. Here is the link on MSDN: Substitutions

So here is the info: You only need escaping the dollar sign, so the code would look like this:

Regex reg=new Regex("Text to replace",RegexOptions.CaseInsensitive);

string s="here is the text to replace";

s=Regex.Replace(s,"$${0}");

Now the value of s is "here is the ${0}".

2 comments:

Chris Martin said...

Thank you so freakin' much for this little nugget!

I was about to loose it. lol

Siderite said...

You are welcome. Nice blog.