Lua Pattern matching string.find (Introduction)


Example

The find function

First let's take a look at the string.find function in general:

The function string.find (s, substr [, init [, plain]]) returns the start and end index of a substring if found, and nil otherwise, starting at the index init if it is provided (defaults to 1).

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

Introducing Patterns

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

All except the following characters represent themselves ^$()%.[]*+-?). Any of these characters can be represented by a % following the character itself.

("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