Insert Text or Parts of The Match Before and After The Match

This example demonstrates how you can prepare a search-and-replace action with RegexMagic to insert text before the regex match. In a regular expression, metacharacters need to be escaped. This example prepares a search-and-replace that does this. You could use this to insert a user-provided search term into a regular expression, for example. You can find this example as “Action: insert before and after match” in the RegexMagic library.

For this example, we’ll continue with the regular expression created in the example about the “regex metacharacter” pattern. That regular expression matches the metacharacters we want to escape. All we need to do is to use the settings on the Action panel to insert the escape character.

  1. On the Library panel, load RegexMagic.rml if it isn’t loaded already.
  2. In the list of RegexMagic formulas in the library, select “Pattern: regex metacharacter”.
  3. Click the Use button to populate the Samples, Match, and Action panels with the settings from the RegexMagic formula we just selected.
  4. On the Action panel, select “insert before and after match” in the “action to take” drop-down list.



  5. Set “insert before replacement” to “insert literal text”.
  6. Enter a literal backslash as the “insert before replacement”.
  7. On the Regex panel, select “Python 3.13” as your application, turn off free-spacing, and turn off mode modifiers. Click the Generate button. The regular expression is the same one that matches a single metacharacter. This example adds the replacement text that inserts the backslash:
    \\\g<0>

You could add the same action to the example about the “replacement metacharacter” pattern in order to escape metacharacters in replacement texts. Depending on your application’s replacement text syntax, the escape character to insert may need to be a dollar sign rather than a backslash.

Related Examples

Reference