Contact Us 1-800-596-4880

Use Regular Expressions in DataWeave

Several DataWeave functions accept regular expressions as arguments, which you can use to return or check for matches. You can also construct regular expressions that incorporate DataWeave expressions that include functions and variables.

Before you begin, note that 2.x versions of DataWeave are used by Mule 4 apps. For DataWeave in Mule 3 apps, refer to DataWeave version 1.2 examples. For other DataWeave versions, you can use the version selector in the DataWeave table of contents.

Return Matches from a String

This example uses regular expressions in a number of DataWeave functions to return matches to an input variable "mycompany.com".

  • contains returns true based on a regular expression that matches part of the input string.

  • find returns an array of indices that specify the matching locations in the input string. This function treats the input string as a string array.

  • match returns an array of substrings that match the regular expression.

  • matches returns true because the regular expression matches the input string exactly.

  • replace returns a URL that changes .com in the input string to .net, based on the regular expression \..*m.

  • scan returns a subarray of comma-separated substrings that the regular expression matches.

  • splitBy splits an input string into an array of substrings based on the . in the input.

DataWeave Script:
%dw 2.0
var myString = "mycompany.com"
output application/json
---
{
	"contains" : myString contains(/c.m/),
	"find" : myString find(/[m|n].|m$/),
	"match" : myString match(/([a-z]*).[a-z]*/),
	"matches" : myString matches(/([a-z]*).[a-z]*/),
	"replaceWith" : myString replace /\..*m/ with ".net",
	"scan" : myString scan(/([a-z]*).(com)/),
	"splitBy" : myString splitBy(/[.\/]/)
}
Output JSON:
{
  "contains": true,
  "find": [
    [
      0
    ],
    [
      4
    ],
    [
      7
    ],
    [
      12
    ]
  ],
  "match": [
    "mycompany.com",
    "mycompany"
  ],
  "matches": true,
  "replaceWith": "mycompany.net",
  "scan": [
    [
      "mycompany.com",
      "mycompany",
      "com"
    ]
  ],
  "splitBy": [
    "mycompany",
    "com"
  ]
}

For function documentation, see:

Use DataWeave Variables and Functions in a Regular Expression

This example constructs a regular expression by using the DataWeave concatenate function (++) to incorporate a DataWeave variable into a regular expression. The regular expression matches "somebiz". The example uses replace and with to replace "somebiz" with "abcd".

DataWeave Script:
%dw 2.0
var myCompany = { "name" : "biz" }
var myInputA = "somebiz-98765"
output application/json
---
{
  example: myInputA replace (("(^s.*e)" ++ myCompany.name) as Regex) with ("abcd")
}
Output JSON:
{
  "example": "abcd-98765"
}