string.find() function in Lua


string.find() is one of the most powerful library functions that is present inside the string library.

Lua doesn’t use the POSIX regular expression for pattern matching, as the implementation of the same takes 4,000 lines of code, which is actually bigger than all the Lua standard libraries together. In place of the POSIX pattern matching, the Lua’s implementation of pattern matching takes less than 500 lines.

The string.find() function is used to find a specific pattern in a given string, it normally takes two arguments, the first argument being the string in which the pattern we are trying to search, and the second argument is the pattern that we are trying to search.

There’s a third argument also, the third argument is an index that tells where in the subject string to start the search. This parameter is useful when we want to process all the indices where a given pattern appears. It is mainly used where there are chances that multiple times a same pattern will occur in the same string.

Syntax

indexstart, indexend = string.find(s,”pattern”)
or
indexstart, indexend = string.find(s,”pattern”,indexstart + z)

In the above syntax, I mentioned both the types of the string.find() function that we can make use of.

Example

Let’s consider a very simple example of the string.find() function where we will try to find a simple pattern in a given string.

Consider the example shown below −

 Live Demo

s = "hello world"
i, j = string.find(s, "hello")
print(i, j)

Notice that in the above code, the i identifier is the starting index where the pattern that we search was found, the j identifier is the ending index of that pattern.

Output

1 5

There might be scenarios where we would want to use only one of these indexes and in those cases, we can simply write the code as follows.

Example

Consider the example shown below −

_, y = string.find(s,"world")
print(y)
x, _ = string.find(s,"world")
print(x)

Output

11
7

Let’s explore one more example where we will make use of the third argument.

Example

Consider the example shown below −

s = "hello n hello y hello z"
index = string.find(s,"hello",i+1)
print(index)

Output

9

Updated on: 19-Jul-2021

17K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements