Parameterizing a Regular Expression Stored in a Library

When storing a regular expression in a RegexBuddy Library for later reuse, it is sometimes obvious that many variants of the regex should also be in the library. E.g. the regex ^.{7}(.{3}) captures the 8th through 10th characters of a line into backreference 1. Though you may want to store this regex for later reuse, it is quite likely that in the future, you will use the same technique to capture a different range of characters.

Rather than storing a large number of similar regexes into a library, you can parameterize a regular expression. Replace all parts of the regex that should be variable, with a parameter. A parameters is a sequence of one or more letters A..Z and digits 0..9, delimited by a pair of percentage signs. E.g. turn ^.{7}(.{3}) into ^.{%SKIPAMOUNT%}(.{%CAPTUREAMOUNT%}). Then add the regex to the library. It doesn’t matter if adding the parameters makes the regular expression invalid on the Create panel. The library will accept it and detect the parameters.

When you’ve selected a regex with parameters in the library, a new grid appears on the Library panel. This grid has three columns. It has one row for each parameter you inserted into the regex. In the second column, briefly describe the parameter. For lengthy descriptions, use the edit box just below the Library panel’s toolbar instead. There, you can enter as much text as you want.

Provide a default value for each parameter in the third column. Substituting each parameter with its default value should result in a valid regular expression. That makes it easier to reuse the regex later.

When substituting a regular expression, RegexBuddy does not interpret a parameter’s value in any way. The parameter’s tag is simply replaced with the value, whatever it is. Metacharacters in the value are not automatically escaped. Though this means you have to be a bit careful when entering a value for a parameter, it also enables you to substitute a parameter with a complete regular expression. The above example could be generalized into ^.{%SKIPAMOUNT%}(%REGEX%). Rather than capturing a fixed number of characters, this regex template matches whichever regular expression you want, starting at a specific column on a line.

When adding a replace action to a library, you can use parameters in the replacement text just like you can use them in the regular expression. If you specify the same parameter more than once, in the regex and/or the replacement text, all occurrences of that parameter are replaced with the same value.