Regex replace with capturing groups




VS Code


Regular expressions with capturing groups are super useful for text replacements, and Visual Studio, VS Code, and notepad++ all support them. They can prevent you from doing a lot of boring work, such as:

public string Name {get;set; }

Simple example

We have this CSV file header and want to make it a full C# class.

Id Name Value ...20 more properties...

We could add a new line after every word, and then write in the property definition manually, which is boring, and hard when Visual Studio tries to make sense of your broken “code”.

OR we can just replace every word with the correct definition, with the captured word in the middle. Something like this:

public string <the word> { get; set; }<new line>

Expressing this in regular expression replacement looks like this:

find:     (\w+)
replace:  public string $1 { get; set; }\n`

Where $1 is replaced with the first capturing group, and \n is expanded to a new line.

After the replacement you get this:

public string Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
//... 20 more properties

All we then need to do is sorround the properties with a class defintion.

This is just a simple example, here is a full video showing other examples, and how exactly you do this: youtube 29:20 with some more hardcore example: youtube 47:39.

written at