Sunday 12 March 2017

Finding a Hyphenated Sub-String of a String in Lua

The Lua string module has a find function which locates a specified sub-string with a longer string. It seems intuitive that the function looks for a string within a string.

    > str = 'A string containing abc-def amongst other things'
    > =string.find(str, 'amongst')
    29    35

However, what isn't clear from that example that the second argument to Lua's find function is not a simple string but a pattern. A '-' is a "reserved" symbol in a Lua pattern so if you simply search for a string containing one, you will most probably not find it.

    > =string.find(str, 'abc-def')
    nil

The '-' character  in a pattern means "Match the previous character (or class) zero or more times, as few times as possible." It can be "escaped" with the '%' character.

    > =string.find(str, 'abc%-def')
    21   27

Alternatively, the find function accepts a fourth parameter which turns off pattern matching and your search will return the expected result. (In order to use it, you must also supply the third parameter which tells the find function where to start its search).

    > =string.find(str, 'abc-def', 1, true)
    21        27


No comments: