replace()

The replace() function finds all occurrences of a specified pattern in a target string and replaces them with a replacement string. By default, literal string matching is performed. When the flag is set to "re", the pattern is interpreted as a regular expression.

Syntax

replace(TARGET, PATTERN, REPLACEMENT[, FLAG])

Parameters

TARGET
The original string field or value to perform the replacement on.
PATTERN
The pattern string to search for. If FLAG is "re", this is interpreted as a regular expression.
REPLACEMENT
The string to substitute for each match. If null, it is treated as an empty string.
FLAG
(Optional) When set to "re", PATTERN is interpreted as a regular expression for replacement.

Description

The replace() function returns a string with all occurrences of PATTERN in TARGET replaced by REPLACEMENT.

  • If TARGET is null, the function returns null.
  • If PATTERN is null, TARGET is returned as-is.
  • If REPLACEMENT is null, it is treated as an empty string ("").
  • If FLAG is omitted or set to any value other than "re", literal string matching is used.
  • If FLAG is "re", java.util.regex.Pattern is used to perform a full regular expression substitution (replaceAll).

Error codes

N/A

Usage examples

To prepare the WEB_APACHE_SAMPLE table used in these examples, refer to Preparing sample data.

  1. Remove a specific path prefix from a URI

    table limit=5 WEB_APACHE_SAMPLE | eval result = replace(uri, "/archives/", "/") | fields uri, result
    
  2. Mask numeric IDs in a URI using a regular expression pattern

    table limit=5 WEB_APACHE_SAMPLE | eval result = replace(uri, "[0-9]+", "{id}", "re") | fields uri, result
    | # result: "/archives/{id}", etc.
    
  3. Substitute using regular expression capture groups

    json "{'s': 'A:2 B:3 C:5'}" | eval result = replace(s, "A:(\\d+) B:\\d+ C:(\\d+)", "$1 $2", "re")
    | # result: "2 5"
    
  4. NULL input

    json "{'msg': null}" | eval result = replace(msg, "world", "logpresso")
    | # result: null
    

Compatibility

The replace() function is available since before Sonar 4.0.