Regular expression replace in Visual Studio 2010

I can never remember how to do replaces in Visual Studio using regular expressions, so here’s a quick example.

I’ve got 30 classes that implement BasePage. I want to change this:

public class VariationsPage : BasePage

to this:

public class VariationsPage : BasePage<VariationsPage>

The regex should find:

public class {.*} \: BasePage

and replace with:

public class \1 \: BasePage<\1>

Edit: the syntax changed in Visual Studio 2012 and onwards! Instead of {.*} and \1 it is now (.*) and $1.

Advertisement

3 thoughts on “Regular expression replace in Visual Studio 2010

  1. doesn’t work , need help!!!
    i want to find:
    RaisePropertyChanged(“x”);
    and to replace with:
    RaisePropertyChanged(=> x);

    x-can be all string

    • Hello gili,

      What version of Visual Studio are you using? I think my blog post was written using Visual Studio 2010. It looks like the syntax has changed to use $1 for substitutions instead of \1, according to this page:
      https://msdn.microsoft.com/en-us/library/2k3te2cs%28v=vs.120%29.aspx

      “For example, the grouped regular expression (\d)([a-z]) finds four matches in the following string: 1a 2b 3c 4d. The replacement string z$1 converts that string to z1 z2 z3 z4> The equivalent syntax in Visual Studio 2010 is {:z}([a-z]) for the grouped regular expression and z\1 for the replacement string.”

      I have just tested this on Visual Studio 2013 (which is the only version I have installed), and this works:

      Find:
      RaisePropertyChanged\(“(.*)”\);

      ​Replace:
      ​RaisePropertyChanged(=> $1);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s