Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 350
Aidiakapi Avatar asked Jul 06 '12 14:07

Aidiakapi


2 Answers

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.

like image 64
Bart Kiers Avatar answered Sep 21 '22 09:09

Bart Kiers


In Lua, the parentheses are only used for capturing. They don't create atoms.

The closest you can get to the patterns you want is:

'^flyi?n?g?$'
'^en?g?l?i?s?h?$'

If you need the full power of a regular expression engine, there are bindings to common engines available for Lua. There's also LPeg, a library for creating PEGs, which comes with a regular expression engine as an example (not sure how powerful it is).

like image 39
Mud Avatar answered Sep 22 '22 09:09

Mud