Function: replace

Function: replace

Usage

 replace(some_string, match: regular expression, replace: replacement, in_context: regular expression)

Replace all matches of a regular expression with a replacement value. The replacement can either be a string or a function.

  • The string can contain backreference "\\0", "\\1", etc. refering to the components captured by the parentheses in the regular expression.
  • When the replacement is a function, the variable input contains the whole match and _1, _2, etc. contains the components.

Optionally a context can be given. The replacement is only performed if the string where the match is represented as <match> also matches the context.

When the replace is used many times with the same match or in_context values it is more efficient to declare these as default arguments:

 my_replace := replace@(match: "something", replace: "something else")
 my_replace("input") # called many times

This way the regular expression is compiled only once.

Note: Avoid using in_context, since it is quite slow. Consider using lookahead and lookbehind assertions first if possible.

Parameters

Parameter Type Description
input string String to replace in.
match regex Regular expression to match.
replace string or function Replacement
in_context regex (optional) Context to match

Examples

 replace(match: "a", replace: "e", "banana")  ==  "benene"
 replace(match: "a", replace: "e", in_context: "<match>n", "banana")  ==  "benena"
 replace(match: "(a|b)x", replace: "[\\0,\\1]", "axabxc")  ==  "[ax,a]a[bx,b]c"
 replace(match: "[ab]", replace: to_upper, "banana")  ==  "BAnAnA"
 replace(match: "([0-9])[*]([0-9])", replace: { _1 * _2 }, "2*2+3*3")  ==  "4+9"

 f := replace@(match: "xx+", replace: "A")
 f("xyzxxyyzz") == "xyzAAyyzz"

See also

filter_text Keep only the text matching a regular expression.