Find and Replace Regular Expression in VS 2012

Category: c# ide

Question

Don-Rule on Tue, 21 Aug 2012 00:33:07


I would like to replace all the arrays in a class with generic lists. E.g.

public string[] strings; becomes public List<string> strings;

I have a Find expresssion that seems to be working:

public\s(\w+)\[\]\s(\w+)

But my Replace does not

public List<\1> \2

what I end up with is

public List<\1> \2

I am not sure if the find did not register the references or if the replace did not recognize the backreferences.

Any clues would be greatly appreciated,

Don Rule
http://translationalsoftware.com

Replies

CoolDadTx on Tue, 21 Aug 2012 02:51:27


To find the above text use this:

public\s+(?<type>\w+)\[\s*\]

This matches all public arrays.  If you want to replace all arrays then remove public.

To reference the named group in a replacement string you have to use the substitution syntax.  The syntax you were using is for when you are backtracking, not replacing.  Here's the corresponding replacement string.

public List<${type}>

Michael Taylor - 8/20/2012
http://msmvps.com/blogs/p3net

Don-Rule on Tue, 21 Aug 2012 21:24:46


Thanks very much.

Aron D Curzon on Fri, 07 Sep 2012 19:13:18


Use $1 instead of \1.

The regular expression syntax changed between VS2010 and VS2012.

VS2012 Regex - http://msdn.microsoft.com/en-us/library/2k3te2cs(v=vs.110).aspx

VS2010 Regex - http://msdn.microsoft.com/en-us/library/2k3te2cs(v=vs.100).aspx