2 likes
·
61 reads
3 comments
Great intro to Regex!
It's not just in programming logic that Regex can help. Some editors like Visual Studio and VS Code allow doing find/replace with Regex.
I like using VS Code because it gives live feedback for the search expression. By using capture groups, it's possible to do lots of code replacements that would otherwise take a while if done manually.
Thank you, Anthony! I know regex is available in VS Code search but I never use it. Any resources or information about it?
Fabien Schlegel I don’t know of any off the top of my head. But at a high level, it’s the button where the icon looks a bit like .*
. When you toggle that on, the search bar matches uses Regex rather than plain text. You can use any of the regex expressions described in this article. The most powerful thing about it is creating capture groups.
Let’s say I’m writing a unit test in C#, and I have a constructor like this:
public class MyClass
{
public MyClass(
MyInterface1 myInterface1,
MyInterface2 myInterface2)
{
}
}
Suppose I now want to write some mocks to pass into the constructor. I can copy/paste the parameter list, and then do a find for
([a-z0-9]+) ([a-z0-9]+)
And replace it with
var $2 = new Mock<$1>();
I would then end up with the following:
var myInterface1 = new Mock<MyInterface1>();
var myInterface2 = new Mock<MyInterface2>();
This works by matching a group of letters and numbers, a space, and then another group of letters and numbers. Each group is captured by wrapping the subexpression in ()
.
We can access the groups using $1 for the first group, $2 for the second, and so on. By using them in the Replace field, we have managed to write some new code using find/replace.
This example is fairly simple because our types are very similar, and we only have two parameters. But it can be a huge time saver for more complex code though.