string.match()

Type Function
Library string.*
Return value String
Revision Release 2024.3703
Keywords string, match, find
See also string.gmatch()
string.find()

Overview

Extract substrings by matching a pattern in a string. If a match is found, returns the captures from the pattern; otherwise returns nil. If pattern specifies no captures, then the whole match is returned.

Syntax

string.match( s, pattern [, init] ) 

s:match( pattern [, init] )
s (required)

String. Any string.

pattern (required)

String. Specifies the pattern to match. See Lua String Manipulation.

init (optional)

Number. Number specifying where in s to start the search. The default is 1; can be negative.

Example

print( string.match( "I have 2 questions for you.", "%d+ %a+" ) )  --> 2 questions
 
print( string.format( "%d, %q", string.match( "I have 2 questions for you.", "(%d+) (%a+)" ) ) )  --> 2, "questions"