string.find(简介)

find 功能

首先让我们来看看 string.find 函数:

函数 string.find (s, substr [, init [, plain]]) 返回子字符串的开始和结束索引(如果找到),否则返回 nil,如果提供则返回索引 init(默认为 1)。

("Hello, I am a string"):find "am" --> returns 10 11
-- equivalent to string.find("Hello, I am a string", "am") -- see remarks

介绍模式

("hello world"):find ".- " -- will match characters until it finds a space
    --> so it will return 1, 6

除了以下字符之外的所有字符代表自己^$()%.[]*+-?)。任何这些字符都可以由字符本身后面的%表示。

("137'5 m47ch s0m3 d1g175"):find "m%d%d" -- will match an m followed by 2 digit
    --> this will match m47 and return 7, 9

("stack overflow"):find "[abc]" -- will match an 'a', a 'b' or a 'c'
    --> this will return 3 (the A in stAck)

("stack overflow"):find "[^stack ]"
    -- will match all EXCEPT the letters s, t, a, c and k and the space character
    --> this will match the o in overflow

("hello"):find "o%d?" --> matches o, returns 5, 5
("hello20"):find "o%d?" --> matches o2, returns 5, 6
    -- the ? means the character is optional

("helllllo"):find "el+" --> will match elllll
("heo"):find "el+" --> won't match anything

("helllllo"):find "el*" --> will match elllll
("heo"):find "el*" --> will match e

("helelo"):find "h.+l" -- + will match as much as it gets
    --> this matches "helel"
("helelo"):find "h.-l" -- - will match as few as it can
    --> this wil only match "hel"

("hello"):match "o%d*"
    --> like ?, this matches the "o", because %d is optional
("hello20"):match "o%d*"
    --> unlike ?, it maches as many %d as it gets, "o20"
("hello"):match "o%d"
    --> wouldn't find anything, because + looks for 1 or more characters