DataWeave Delight: Wrapping string values
If we want to wrap a string value with another string value we can use the wrapWith
and wrapIfMissing
functions defined in the dw::core::Strings
module. The first argument of these functions is the string we want to wrap and the second argument is the string value that wraps the first argument. The function wrapIfMissing
will only apply the wrapper string if it was not already applied.
To remove a wrapped character from a wrapped string we can use the unwrap
function. The first argument is the string value that is already wrapped and the second argument the character we want to use for unwrapping. The second argument can only be a single character, but we can repeatedly invoke the unwrap
function to remove multiple wrap characters.
In the following example we use all three functions in different ways:
Source
%dw 2.0
import wrapWith, wrapIfMissing, unwrap from dw::core::Strings
output application/json
---
{
wrapWith: {
// Wrap with single quotes
sample1: wrapWith("DataWeave", "'"),
// Even if already wrapped, keep on wrapping
sample2: wrapWith("'DataWeave'", "'"),
// We can use more than one character to wrap
sample3: wrapWith("DataWeave", "{data}"),
// Using infix notation
sample4: "mrhaki" wrapWith "__"
},
wrapIfMissing: {
// Wrap value only if not already wrapped
sample1: wrapIfMissing("DataWeave", "'"),
// If already wrapped with given value then don't wrap
sample2: wrapIfMissing("'DataWeave'", "'")
},
unwrap: {
// Remove wrapping character(s)
sample1: unwrap("'DataWeave'", "'"),
// If given wrap characters are not used, return the value
sample2: unwrap("DataWeave", "'"),
// Unwrap with more than one character only removes one wrap character
sample3: unwrap("##DataWeave##", "##"),
// Unwrap with more than one character gives unexpected results
sample4: unwrap(unwrap("##DataWeave##", "#"), "#"),
// With infix notation
sample5: ("##DataWeave##" unwrap "#") unwrap "#"
}
}
Output
{
"wrapWith": {
"sample1": "'DataWeave'",
"sample2": "''DataWeave''",
"sample3": "{data}DataWeave{data}",
"sample4": "__mrhaki__"
},
"wrapIfMissing": {
"sample1": "'DataWeave'",
"sample2": "'DataWeave'"
},
"unwrap": {
"sample1": "DataWeave",
"sample2": "DataWeave",
"sample3": "#DataWeave#",
"sample4": "DataWeave",
"sample5": "DataWeave"
}
}
Written with DataWeave 2.4.
DataWeave is a functional language designed by MuleSoft for transforming data structures defined in for example JSON, XML or CSV. |