Search code examples
regexlualua-patterns

Lua pattern parentheses and 0 or 1 occurrence


I'm trying to match a string against a pattern, but there's one thing I haven't managed to figure out. In a regex I'd do this:

Strings:
en
eng
engl
engli
englis
english

Pattern:
^en(g(l(i(s(h?)?)?)?)?)?$

I want all strings to be a match. In Lua pattern matching I can't get this to work.

Even a simpler example like this won't work:

Strings:
fly
flying

Pattern:
^fly(ing)?$

Does anybody know how to do this?


Solution

  • You can't make match-groups optional (or repeat them) using Lua's quantifiers ?, *, + and -.

    In the pattern (%d+)?, the question mark "looses" its special meaning and will simply match the literal ? as you can see by executing the following lines of code:

    text = "a?"
    first_match = text:match("((%w+)?)")
    print(first_match)
    

    which will print:

    a?
    

    AFAIK, the closest you can come in Lua would be to use the pattern:

    ^eng?l?i?s?h?$
    

    which (of course) matches string like "enh", "enls", ... as well.