Why does this sting.find fail?
Asked Answered
P

1

6
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 succeed?

string.find("MOZ-MAIL-1-1","Z-MAIL-")
Pout answered 31/5, 2024 at 0:46 Comment(0)
P
11

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.

Purlieu answered 31/5, 2024 at 0:57 Comment(1)
thank you.. addition because i cant simply say thank youPout

© 2022 - 2025 — McMap. All rights reserved.