string.find()

The string.find() function searches for a pattern within a string and returns the starting and ending indices of the first match. It is commonly used for pattern matching or substring searching.

Syntax

string.find(s, pattern, init, plain)

Parameters

  • Name
    s
    Type
    string
    Description

    The string to search within.

  • Name
    pattern
    Type
    string
    Description

    The pattern to search for. This can be a plain string or a Lua pattern.

  • Name
    init
    Type
    number
    Description

    The starting position for the search. Defaults to 1. Negative values count from the end of the string.

  • Name
    plain
    Type
    boolean
    Description

    If true, disables pattern matching and treats the pattern as a plain string. Defaults to false.

Return Value

  • If a match is found: Returns the start and end indices of the first occurrence of the pattern, and any captured substrings (if applicable).
  • If no match is found: Returns nil.

Examples

Example 1: Basic search

Search for a substring in a string.

Example 1

local text = "The quick brown fox"
local startIndex, endIndex = string.find(text, "quick")

print(startIndex, endIndex) 
-- Output: 5 9

Example 2: Using patterns

Search for the first word starting with a vowel.

Example 2

local text = "The quick brown fox"
local startIndex, endIndex = string.find(text, "%a*[aeiou]%a*")

print(startIndex, endIndex)
-- Output: 5 9 (matches "quick")

Example 3: Starting position (init)

Specify where the search begins.

Example 3

local text = "The quick brown fox jumps"
local startIndex, endIndex = string.find(text, "fox", 11)

print(startIndex, endIndex)
-- Output: 17 19

Example 4: Plain search

Disable pattern matching with plain.

Example 4

local text = "The quick [pattern] fox"
local startIndex, endIndex = string.find(text, "[pattern]", 1, true)

print(startIndex, endIndex)
-- Output: 11 19

Example 5: No match

Handle cases where the pattern is not found.

Example 5

local text = "The quick brown fox"
local result = string.find(text, "cat")

print(result)
-- Output: nil

Use Cases

  • Substring Search: Find specific words or characters in a string.
  • Pattern Matching: Use Lua patterns to identify substrings that match specific criteria.
  • Custom Search: Limit the search range with init or perform literal matches with plain.

See also

  • string.match(): Extracts the first substring that matches a pattern.
  • string.gmatch(): Iterates over all substrings in a string that match a pattern.
  • string.gsub(): Replaces all occurrences of a pattern in a string with a replacement string.
  • string.sub(): Extracts a substring using start and end indices.

Was this page helpful?

Table of Contents