Since I understood how complicated, slow and troublesome regular expressions can be, I always tried to solve my programming problems (ekhm… challenges) without them. But some time ago, when I get involved into refactoring of huge banking system, I realized that this is not the case anymore. Regex can be very useful in certain cases…
The purpose of this note is to notify others that regex can be useful while working with the code and to hold all my most useful regex tips.
I have an SQL query and I’d like to create variables based on them. What to do? Of course, I can do it manually. I can also use regex 😛
At the first glance, it is not an easy task. First, I will copy the SQL into the foreach loop.
So, I copied SQL, selected it, pressed CTRL-H and clicked the asterisk button that enables regex in the search&replace action. Now the trickiest part – what do I want to replace with what?
Search text box: \$.*Print(.*)\.(.*)\).*
Replace text box: var \l$2 = row.GetCellValue(nameof(Print$1.$2));
What does it mean? The heart of the regex above is the group feature. It means that the group found by regex can be used in the replacement statement. Groups are enclosed by parenthesis and indexed starting from 1. Then, in the replacement, it can be referred to with the dollar sign.
After the above was applied, the selection changed to:
The replacement string refers to the groups found by the regex:
This example shows how to use regexes in the IDE. For such small changes, regex seems kinda like shooting a fly with a cannon, but it’s worth considering when we work with the bigger files. Especially with the „magical recipies”:
I found them here, if you like it, give a kudos!
Find: (\s)([a-z]) (\s also matches new lines, i.e. „venuS” => „VenuS”)
Remove camel case (e.g. cAmelCAse => camelcAse => camelcase)
Lowercase letters within words (e.g. LowerCASe => Lowercase)
Alternate Replace: \L$0
Uppercase letters within words (e.g. upperCASe => uPPERCASE)
Uppercase previous (e.g. upperCase => UPPERCase)
Lowercase previous (e.g. LOWERCase => lowerCase)
Uppercase the rest (e.g. upperCase => upperCASE)
Lowercase the rest (e.g. lOWERCASE => lOwercase)
Shift-right-uppercase (e.g. Case => cAse => caSe => casE)
Shift-left-uppercase (e.g. CasE => CaSe => CAse => Case)
That’s it. As I said, I hope that this note will inspire you to at least give regex a try. I started to use it and if I find something useful, I will add it to this page. The magical recipes listed above are a good start, we can do a lot with them.
I almost forgot. I use Rider & Visual Studio 2022. Sometimes IDE differs slightly when comes to regex handling. If the examples don’t work for you, look here.