format()

The format() function generates and returns a new string using a format string and arguments.

Syntax

format(FORMAT_STR, PARAM1[, PARAM2, ...])

Parameters

FORMAT_STR
A format string containing format specifiers. Must be specified as a string constant. Refer to the Java Formatter class specification for available format specifiers.
PARAM1[, PARAM2, ...]
The arguments to apply to the format string. Two or more arguments can be specified. If an expression that returns an array, such as array() or groups(), is specified as a single argument, each element of the array is used in order as an argument to the format string.

Description

The format() function operates in the same way as Java's String.format(). It constructs a string by converting each argument according to the format specifiers in FORMAT_STR (such as %s, %d, %f).

If an error occurs during formatting, null is returned.

If FORMAT_STR is not a string constant, error code 91030 is raised and query parsing fails.

Error codes

91030
Raised when FORMAT_STR is not a string constant.

Usage examples

  1. Generate a date format string

    json "{'y': 2024, 'm': 3, 'd': 29}" | eval result = format("date: %04d-%02d-%02d", y, m, d)
    | # result: "date: 2024-03-29"
    
  2. Reorder arguments using an array

    json "{}" | eval result = format("%3$s-%1$s-%2$s", groups("Mar 29 2024", "(.*?) (.*?) (.*)"))
    | # result: "2024-Mar-29"
    
  3. Null returned due to a format error

    json "{'val': 'text'}" | eval result = format("%d", val)
    | # result: null
    

Compatibility

The format() function is available since before Sonar 4.0.