1

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

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

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Alexandre Kirszenberg
  • 35,938
  • 10
  • 88
  • 72

2 Answers2

5

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

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

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")

  • 1
    `"(foo)?bar"` is supposed to be a pattern, where `"foo"` can appear 0 to 1 time and `"bar"` is always supposed to appear. Applied to the `"bar"` string it should logically return the position of `"bar"` but it returns `nil`. – Alexandre Kirszenberg Jan 20 '13 at 13:13
  • @Morhaus Right, check my complete edit. Such a long time since I've been coding lua, didn't remember the pattern matching anymore. –  Jan 20 '13 at 13:18
  • The thing with `[foo]` is that it will match either `"f"` or `"o"`, but I'm trying to match whether `"foobar"` or `"bar"`. – Alexandre Kirszenberg Jan 20 '13 at 13:21
  • @Morhaus Then I'm out of ideas. But I'm sure it can be done somehow –  Jan 20 '13 at 13:24
  • you'll probably have to use two different expressions to do the capture, unfortunately. lua's pattern matching grammar aren't regexs. – Mike Corcoran Jan 20 '13 at 16:05