replace

DataWeave 2.2 is compatible and bundled with Mule 4.2. Standard Support for Mule 4.2 ended on May 2, 2021, and this version of Mule will reach its End of Life on May 2, 2023, when Extended Support ends.

Deployments of new applications to CloudHub that use this version of Mule are no longer allowed. Only in-place updates to applications are permitted.

MuleSoft recommends that you upgrade to the latest version of Mule 4 that is in Standard Support so that your applications run with the latest fixes and security enhancements.

replace(String, Regex): ((Array<String>, Number) -> String) -> String

Performs string replacement.

This version of replace accepts a Java regular expression for matching part of a string. It requires the use of the with helper function to specify a replacement string for the matching part of the input string.

Parameters

Name Description

text

A string to match.

matcher

A Java regular expression for matching characters in the input text string.

Example

The first example in the source replaces all characters up to and including the second hyphen (123-456-) with an empty value, so it returns the last four digits. The second replaces the characters b13e in the input string with a hyphen (-).

Source

%dw 2.0
output application/json
---
["123-456-7890" replace /.*-/ with(""), "abc123def" replace /[b13e]/ with("-")]

Output

[ 7890, "a-c-2-d-f" ]

Example

This example replaces the numbers 123 in the input strings with ID. It uses the regular expression (\d+), where the \d metacharacter means any digit from 0-9, and + means that the digit can occur one or more times. Without the +, the output would contain one ID per digit. The example also shows how to write the expression using infix notation, then using prefix notation.

Source

%dw 2.0
output application/json
---
[ "my123" replace /(\d+)/ with("ID"), replace("myOther123", /(\d+)/) with("ID") ]

Output

[ "myID", "myOtherID" ]

replace(String, String): ((Array<String>, Number) -> String) -> String

Performs string replacement.

This version of replace accepts a string that matches part of a specified string. It requires the use of the with helper function to pass in a replacement string for the matching part of the input string.

Parameters

Name Description

text

The string to match.

matcher

The string for matching characters in the input text string.

Example

This example replaces the numbers 123 from the input string with the characters ID, which are passed through the with function.

Source

%dw 2.0
output application/json
---
{ "replace": "admin123" replace "123" with("ID") }

Output

{ "replace": "adminID" }

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub