string.match()

类型 函数
string.*
返回值 字符串
修订版 发行版 2024.3703
关键字 string、match、find
另请参阅 string.gmatch()
string.find()

概述

通过匹配字符串中的模式来提取子字符串。如果找到匹配项,则返回模式中的捕获项;否则返回 nil。如果 pattern 未指定任何捕获项,则返回整个匹配项。

语法

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

s:match( pattern [, init] )
s (必需)

String. 任何字符串。

pattern (必需)

String. 指定要匹配的模式。请参阅 Lua 字符串操作

init (可选)

Number. 指定从 s 中的何处开始搜索的数字。默认值为 1;可以为负值。

示例

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"