String interpolation

String interpolation is an alternative to building strings via concatenation.

String interpolation provides a more readable and convenient syntax to create formatted strings:

  • Build strings using a mix of literals, constants, and variables.
  • Concatenate elements without using the concatenation operator +.
  • Produce multiline strings.
  • Format locale-sensitive information.

The following example shows two expressions that would produce the same output, using string concatenation and string interpolation:

// String concatenation:
set decision to Greeting + ", " + 'Courtesy Title' + " " + the last name of Person + "!" ;
// String interpolation:
set decision to `{ Greeting }, { 'Courtesy Title' }{ the last name of Person } !` ;
// Both would produce the same output, for example:
Good morning Mr. Jones!

Syntax

Interpolated strings are delimited with backtick characters ( ` ). Their syntax is as follows:

`<text>? ( {<interpolationExpression> [:<format>] }  <text>?)*`

The <text> and <format> elements ares optional. The following table lists the details of each element:

Element Description
text Any type of literal text.
interpolationExpression A rule language expression that produces a result to be formatted.
format A string format used to format the resulting expression as a string.
Note: Only the Java Format class and its subclasses are supported.

To include a brace, ( { or } ), in the text produced by an interpolated string, use escaped braces, ( /{ or /} ).

Examples

The following example shows a multiline interpolated string that contains a list of values, including a formatted date:

print `Name: {the name of John},
famous: {John is famous},  
birth date: {the birth date of John:date,short}, 
hair color: {the hair color of John},  
category: {the category of John}.`;

The expected output would be similar to:

`Name: John,
famous: true,  
birth date: Feb 4, 1977, 
hair color: brown,  
category: silver.`;

The following example shows a single line interpolated string that contains a formatted number:

print `Pi = {Value:number,#.##}`;

If Value = 3.141592653589793, the expected output would be:

Pi = 3.14