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
FLAGis"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",PATTERNis 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
TARGETisnull, the function returnsnull. - If
PATTERNisnull,TARGETis returned as-is. - If
REPLACEMENTisnull, it is treated as an empty string (""). - If
FLAGis omitted or set to any value other than"re", literal string matching is used. - If
FLAGis"re",java.util.regex.Patternis 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.
-
Remove a specific path prefix from a URI
table limit=5 WEB_APACHE_SAMPLE | eval result = replace(uri, "/archives/", "/") | fields uri, result -
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. -
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" -
NULL input
json "{'msg': null}" | eval result = replace(msg, "world", "logpresso") | # result: null
Compatibility
The replace() function is available since before Sonar 4.0.