replace using regex in Dataweave

Input

$filter=FirstName eq 'LISA'&$select=Id,CoveredSkus,FirstName&

My Script to remove the "select" query param

%dw 2.0
output application/java
---
payload replace "\$select=.*?(&|\$)"  with ""

Expected Output

$filter=FirstName eq 'LISA'&

Actual Output

$filter=FirstName eq 'LISA'&$select=Id,CoveredSkus,FirstName&

What am I doing wrong here ? I do see this regex works in matching the correct substring as shown here – https://regex101.com/r/2RZoPX/1

If there is another way to remove the "select" data, I am open to that aswell

>Solution :

Your regex is correct, you are just using the wrong way to use regex in replace. Regex needs to be enclosed in ‘//’ instead of "".
Try like this for regex:

%dw 2.0
output application/json
---
payload replace /\$select=.*?(&|\$)/  with ""

Alternate way with SubstringBefore:

%dw 2.0
output application/json
import * from dw::core::Strings
---
payload substringBefore('\$select')

Leave a Reply