Subroutine to Perform Search/Replace Using Variable Patterns

A user was trying to perform Search/Replace operations using regex patterns stored in KM Variables and ran into a problem as discussed in depth here:

It turns out that if the patterns contain capture groups and their replacement tokens then using KM variables to store these patterns won't work since it would require KM to apply token expansion twice (once for the variable token and secondly for the string held in said variable).

In any case a solution was found and I've created a generally-useful subroutine to easily make use of that solution.

Here are the usage notes for the subroutine:

Purpose
This subroutine lets you perform case insensitive search/replace using regular expressions.

The Search and Replace patterns supplied to the subroutine can either be literal text strings, or be KM variables containing those patterns. Unlike the standard KM Search and Replace action, the KM variables can have text patterns that contain capture groups and capture group references.

Inputs
Local__Input the text to which the search/replace function is to be applied
Local__Search the regular expression search pattern
Local__Replace the regular expression replacement pattern

Output
The text after the search/replace function has been applied.

Note:
The regular expression "flavour" supported by KM is the ICU one which is documented in full here: ICU Regular Expressions

You can download the subroutine here:

Download Macro(s): [SUB] Regex Search Replace with Variables.kmmacros (7.7 KB)

Macro-Image

Macro-Notes
  • Macros are always disabled when imported into the Keyboard Maestro Editor.
    • The user must ensure the macro is enabled.
    • The user must also ensure the macro's parent macro-group is enabled.
System Information
  • macOS 10.14.6
  • Keyboard Maestro v10.2

And here is a simple macro to test the subroutine:

Download Macro(s): Test [SUB] Regex Search Replace with Variables.kmmacros (4.1 KB)

Macro-Image

Keyboard Maestro Export

Macro-Notes
  • Macros are always disabled when imported into the Keyboard Maestro Editor.
    • The user must ensure the macro is enabled.
    • The user must also ensure the macro's parent macro-group is enabled.
System Information
  • macOS 10.14.6
  • Keyboard Maestro v10.2
4 Likes