What is a regular expression for inserting a string into a Find and Replace match?

43 views Asked by At

I need a regular expression to replace all instances of:

Session["ANYWORD"] ==

with

Session["ANYWORD"].ToString() ==

I have Session\["\w+"]\s==, which correctly finds the right matches, but I don't know how to insert .ToString() into the match.

What, or perhaps more appropriately, is there a regular expression to do what I need to do?

1

There are 1 answers

0
MarioDS On BEST ANSWER

You will need to put the value that is between the square brackets into a capture group, and substitute that in your replacement.

In short, this will do it:

Regex.Replace(input, @"Session\[(""\w+"")]\s==", @"Session[$1].ToString() ==");

where $1 will insert the contents of your first capture group (determined by parenthesis in the pattern -> ()).

You can also use named groups if you like, then it becomes:

Regex.Replace(input, @"Session\[(?<anyword>""\w+"")]\s==", @"Session[${anyword}].ToString() ==");

Here is the MSDN doc for that particular overload of Regex.Replace.

For more information about capture group substitution in .NET, look here.