Pattern: Replacement metacharacter

“Replacement metacharacter” is one of the patterns that you can select on the Match panel. This pattern matches a character that has a special meaning in replacement text. Such characters need to be escaped if you want the replacement text to insert them literally. With this pattern you can generate a regex that finds such characters in user input, which you can use to escape those characters before using them in the replacement text.

This example shows how to generate a regex that finds metacharacters. You can use this directly if you want to treat them as errors, for example. You can find this example as “Pattern: replacement metacharacter” in the RegexMagic library. The example “insert before and after match” extends this with an action in order to escape metacharacters.

  1. Click the New Formula button on the top toolbar to clear out all settings on the Samples, Match, and Action panels.
  2. On the Samples panel, paste in one new sample:
     !"#$%&'()*+,-./0123456789:;<=>?
    @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_
    `abcdefghijklmnopqrstuvwxyz{|}~
  3. Set both “begin regex match at” and “end regex match at” to “anywhere”.
  4. Click the Add First Field button to add field 1.
  5. In the “pattern to match field” drop-down list, select “regex metacharacter”.



  6. Tick “regex flavor” and select the flavor if you need to check for metacharacters recognized by the regex engine of a particular application or programming language. Otherwise, the pattern automatically uses the flavor that you select on the Regex panel.
  7. Tick “free-spacing” in the pattern’s settings if you you need to find metacharacters in a string that will be inserted in a regex in free-spacing mode. This is independent of whether you enable free-spacing mode on the Regex panel.
  8. On the Regex panel, select “Python 3.13” as your application, turn off free-spacing, and turn off mode modifiers. Click the Generate button, and you’ll get this regular expression:
    \\
    Unused options: Case sensitive; Exact spacing; Dot doesn’t match line breaks; ^$ don’t match at line breaks.
  9. The Samples panel now highlights all the metacharacters:
     !"#$%&'()*+,-./0123456789:;<=>?
    @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_
    `abcdefghijklmnopqrstuvwxyz{|}~

Related Examples

Reference