Search code examples
lualua-patterns

Why does ("bar"):find("(foo)?bar") return nil?


Shouldn't ("bar"):find("(foo)?bar") return 1, 3?

print(("bar"):find("(foo)*bar")) and print(("bar"):find("(foo)-bar")) won't work either.


Solution

  • This is because parentheses in Lua's patterns (quite unfortunately) do not serve as a grouping construct, only as a delimiters of capturing groups. When you write a pattern (foo)?bar, Lua interprets it as "match f,o,o,?,b,a,r, capture foo in a group". Here is a link to a demo. Unfortunately, the closest you can get to the behavior that you wanted is f?o?o?bar , which of course would also match fbar and oobar, among other wrong captures.

    this code

    print(("bar"):find("f?o?o?bar"))
    

    returns 1 3