Usage of variables in regex

If you want to replace lots of text and all of them are based on the same pattern, it would be stupid to do it manually. To save time and nerves, it’s way better to use regular expressions. One of the most powerful things provided by regular expressions are the variables.


Example
Let’s switch the position of the execution class and the message level of a fictional trace.

1. Initial trace

...
17:02:56.330 [Media.Browser] Info: Folder is empty
17:02:56.332 [Media.Player] Error: Nothing to play
...

3. Desired trace

...
17:02:56.330 [Info] [Media.Browser] Folder is empty
17:02:56.332 [Error] [Media.Player] Nothing to play
...

2. Modification regex

Find:    ^(.*)\s\[(.*)\]\s(.*)\:\s(.*)$
Replace: $1 [$3] [$2] $4
  • ‘^’ … Start of line
  • ‘$’ … End of line
  • ‘.’ … Any character
  • ‘*’ … 0 times til n times
  • ‘\s’ … Whitespace

Everything in a parenthesis get saved in a variable. You can access a variable with ‘$’ followed by the matching position.