Question

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

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

Was it helpful?

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

OTHER TIPS

You're searching for string "(foo)bar" or "(foobar" from string "bar", the questionmark ? only points to the last character.

If you want it to point to the whole word, use [] instead: ("bar"):find("[foo]?bar")

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top