You can use split in OCL to divide a string on one or more delimiter characters; this page is for anyone parsing delimited text in MDriven expressions.
Split a string on character delimiters
split expects an ordered collection of characters as its delimiter argument. An OCL character literal such as 'X' is treated as a string, so convert it with toCharArray before passing it to split.
SomeString.split('X'.toCharArray)For example, this expression splits a comma-separated value into its parts:
'red,green,blue'.split(','.toCharArray)The result is an ordered collection containing 'red', 'green', and 'blue'.
Avoid the string-versus-character error
Do not pass a string literal directly as the delimiter:
SomeString.split('X')This produces the type error:
31:System.String does not conform to Collection(System.Char)
Use 'X'.toCharArray instead.
Split records and create tuples
You can first split a text block into records and then split each record into fields. When a collect body returns comma-separated values, it creates a tuple. The following expression creates one tuple per semicolon-separated record, with Part1 and Part2 holding the values before and after the comma:
'A, B;
X, Y'.Split(';'.toCharArray)->
collect(pair | pair.Split(','.toCharArray)->at(1), pair.Split(','.toCharArray)->at(2))This pattern is useful when you need to iterate over name/value-style input and use each pair in a later expression. For collection behavior, including how OCL flattens nested collections, see Documentation:Examples on collection operators.
Convert an RGB value to a hexadecimal color string
The following expression splits an RGB string, parses each component as an integer, converts each integer to hexadecimal, and joins the results after a # prefix:
RGB := '241, 55, 45';
'#' + RGB.split(','.toCharArray)->
collect(s | Integer.parse(s))->
collect(i | i.toString('x'))->
asSeparatedList('')For the input shown, the resulting string is #f1372d. The split values include leading spaces for the second and third components; Integer.parse accepts the values used in this example.
Join values again
To convert a collection of strings back to one string, use asSeparatedList. For example, the RGB expression uses asSeparatedList() to join hexadecimal components without a separator.
Use asCommaList when you specifically want commas between the values. That page also shows how to split comma-separated text and trim the resulting values.
When split is not the right operator
split is for known delimiter characters. If you need to split wherever a regular-expression pattern matchesâfor example, on commas, semicolons, or whitespaceâuse regExpSplit instead.
For a worked example that extracts hour and minute values from a time string, see Documentation:Split time string to value.
