Showing posts with label Group. Show all posts
Showing posts with label Group. Show all posts

Saturday, December 19, 2015

Group Regex Replace in Visual Studio

Wow, I cannot believe that I did not know about this until now!

We all know that you can use regular expressions to search for things in a document, and we all know that you can replace those matches, but did you know that you can use group matches from your regex in the replace value? Because you can, and it is amazingly useful!

Example: Your class has properties with one attribute containing a value, and you want to add another attribute with the same value.

Find: \[Description\("(\w+)"\)\]

public class MyClass
{
    [Description("A"), DisplayName("A")]
    public string A { get; set; }
 
    [Description("B")]
    public string B { get; set; }
 
    [Description("C")]
    public string C { get; set; }
}

Replace: [Description("$1"), DisplayName("$1")

public class MyClass
{
    [Description("A"), DisplayName("A")]
    public string A { get; set; }
 
    [Description("B"), DisplayName("B")]
    public string B { get; set; }
 
    [Description("C"), DisplayName("C")]
    public string C { get; set; }
}

Enjoy,
Tom

Real Time Web Analytics