Replace
Syntax
$pattern.regexReplace($text, $replacement)
Description
Replaces the occurrences of the given pattern in the given text with the given replacement. The replacement can be either a string or a function.
If the replacement is a string, every search hit in the given text will be replaced by the given replacement string.
If the replacement string contains back references ($1
, $2
,...), they are replaced with the text hit by the referenced group.
If the replacement is a function, it is called with each search hit and generates a dynamic replacement text. The return value of the function can also contain back references.
Parameters
Name | Type | Description | Mandatory | Default |
---|---|---|---|---|
pattern | Business object | The regex pattern to use to search for the string to replace. | yes | |
text | String | The text by which to search for matching search hits to replace. | yes | |
replacement | String/Function | Specifies how the search hits should be replaced. | yes |
Return value
Type: String
The text in which all search hits were replaced.
Examples
Simple replace
regex("a(b+)").regexReplace("XXXabbbYYY", "_")
Output: XXX_YY
The only search hit "abbb" is replaced with a "_".
Replace with reference
regex("a(b+)").regexReplace("XXXabbbYYY", "_$1_")
Output: XXX_bbb_YY
The reference $1
refers to the first group (b+). The search hit "abbb" is replaced by the content of the group "bbb", which is additionally enclosed by "_".
Replace with function
regex("a(b+)").regexReplace("XXXabbbYYY", m -> $m.regexGroup(1).length())
Output: XXX3YY
The search hit "abbb" is replaced by the length of the first group (b+), which equals 3.