Question

According to the docs, all Lua repetition operators only work on single characters, so you can match

string.match('123', '1?(%d+)') -- returns 23

but cannot match multi-character strings:

string.match('123', '(12)?(%d+)') -- want this to return 3

The docs say it's possible through "multiple patterns and custom logic", but I don't know what that means. Can someone offer a way to pattern match the above? Basically, 12 should be optionally matched all-or-nothing, and return the remainder of the digit string.

Was it helpful?

Solution

I think "multiple patterns and custom logic" here means usage like this:

string.match('123', '12(%d+)') or string.match('123', '(%d+)')

Since or is short-circuit, if the first pattern matches, it will be the value of the expresion, otherwise the second pattern will try to match. This is exactly the regex (12)?(%d+) means.

Also note that there are more powerful LPeg or other regex libraries for Lua.

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