substr()

The substr() function returns the substring of a string corresponding to the specified index range.

Syntax

substr(STR, BEGIN[, END])

Parameters

STR
The original string field or value. Non-string values are converted to a string before processing.
BEGIN
The character index at which extraction starts. Indices start at 0. A negative value is counted backward from the end of the string. If the start index is greater than or equal to the string length, or is less than 0 after conversion, null is returned.
END
(Optional) The character index at which extraction ends (exclusive). Indices start at 0. If omitted, extraction continues to the end of the string. A negative value is counted backward from the end of the string. If END is greater than the string length, extraction continues to the end of the string. If BEGIN is greater than END, or END is less than 0 after conversion, null is returned.

Description

The substr() function returns the substring of STR from the BEGIN index (inclusive) to the END index (exclusive).

  • If STR is null, the function returns null.
  • If BEGIN is null, the entire STR is returned.
  • If END equals BEGIN, an empty string ("") is returned.

Error codes

N/A

Usage examples

To prepare the WEB_APACHE_SAMPLE table used in these examples, refer to Preparing sample data.

  1. Extract the first 10 characters of a URI

    table limit=5 WEB_APACHE_SAMPLE | eval result = substr(uri, 0, 10) | fields uri, result
    
  2. Extract the part of a URI after the first / by specifying only the start index

    table limit=5 WEB_APACHE_SAMPLE | eval result = substr(uri, 1) | fields uri, result
    | # result: "feed", "archives/2370", etc.
    
  3. Extract the end of a URI using a negative index

    table limit=5 WEB_APACHE_SAMPLE | eval result = substr(uri, -5) | fields uri, result
    
  4. NULL input

    json "{'val': null}" | eval result = substr(val, 0, 3)
    | # result: null
    

Compatibility

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