stringlua

Why does this string.find fail?


string.find("MOZ-MAIL-1-1","MOZ-MAIL-")
string.find("MOZ-MAIL-1-1","OZ-MAIL-")

Given the above, why do those return false, but the following succeeds?

string.find("MOZ-MAIL-1-1","Z-MAIL-")

Solution

  • string.find uses a pattern by default. - is a special character in a pattern: It is interpreted as "zero or more of the preceding character (class), match lazily".

    To make Lua interpret - as literal - in a pattern, escape it using %: string.find("MOZ-MAIL-1-1","MOZ%-MAIL%-") works.

    An alternative - which is especially convenient if your "needle" is a variable - is to pass a starting position, and to tell Lua to interpret the needle as a literal string by passing a fourth parameter plain = true: string.find("MOZ-MAIL-1-1","MOZ-MAIL-", 1, true) also works.

    string.find("MOZ-MAIL-1-1","Z-MAIL-") succeeds due to a coincidence: It matches MAI in this context: The Z- matches zero Zs, the L- matches zero Ls.