lastindexof()

Returns the index of the last occurrence of a substring in a given string. It returns -1 if the substring is not found; null if either the substring or the string is null.

Syntax

lastindexof(STR_EXPR, SEARCH_EXPR, [FROM_EXPR])
Required Parameter
STR_EXPR
String expression
SEARCH_EXPR
Substring to search for in the string value of STR_EXPR
Optional Parameter
FROM_EXPR

Index (position) from which to start the search. The index counter starts from 0. lastindexof() returns the index of the last occurrence of a substring within a given string, searching backwards to index position 0 starting at a specified index.

The SEARCH_EXPR string does not have to be completely between index 0 and FROM_EXPR. As long as the first index of the SEARCH_EXPR string is within the index range, it will be searched. In usage 5, with FROM_EXPR set to 30 (corresponding to "L"), the range of the "Lo" string is from 30 to 31. But "L" of "Lo" is found at index 30, resulting in the return of 30.

Usages

  1. Find the last index of " ".

    json "{}"
    | eval STR_EXPR="Life is short. Use Logpresso."
    | eval LAST_INDEX=lastindexof(STR_EXPR, " ")
    | # Result: LAST_INDEX = 18
    
  2. Find the index of the last occurrence of "Logpresso".

    json "{}"
    | eval STR_EXPR="Life is short. Use Logpresso."
    | eval LAST_INDEX=lastindexof(STR_EXPR, "Logpresso")
    | # Result: LAST_INDEX = 19
    
  3. When a string does not contain a given substring.

    json "{}"
    | eval STR_EXPR="Life is short. Use Logpresso."
    | eval LAST_INDEX=lastindexof(STR_EXPR, "Python")
    | # Result: LAST_INDEX = -1
    
  4. Specify the search starting position (index) and find the index of the last occurrence of a substring "Lo". Try changing the FROM_EXPR value to get different results.

    # String: Life is short. Use Logpresso. Long live Logpresso!
      Index:  0123456789012345678901234567890
      Range:  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ (0-30)
    | json "{}"
    | eval STR_EXPR="Life is short. Use Logpresso. Long Live Logpresso!"
    | eval SEARCH_EXPR="Lo"
    | eval FROM_EXPR=30
    | eval LAST_INDEX=lastindexof(STR_EXPR, SEARCH_EXPR, FROM_EXPR)
    | # Result: LAST_INDEX = 30
    
  5. Try the function indexof() to compare its result with the lastindexof() function.

    json "{}"
    | eval STR_EXPR = "Life is short. Use Logpresso."
    | eval FIRST_INDEX = indexof(STR_EXPR, " ")
    | eval LAST_INDEX = lastindexof(STR_EXPR, " ")
    | # Result: FIRST_INDEX =  4,
                LAST_INDEX  = 18
    

Compatibility

lastindexof() function is available starting from the release 4.0.2312.0.