Logical 'or' in Lua patterns?

Lua pattern matching is not the same as regular expressions, and does not have an alternation concept.

For example, if you wanted to remove "abc" or "efg" from the end of a string (similar to "(abc|efg)$" regular expression) the following code would work well:

local inputstring="123efgabc"
local s,n = inputstring:gsub("abc$", "")
if n == 0 then
  s,n = inputstring:gsub("efg$", "")
end
print(s) --> 123efg

Lua does not use standard regular expressions for pattern matching. A quote from the book Programming in Lua explains the reason:

Unlike several other scripting languages, Lua does not use POSIX regular expressions (regexp) for pattern matching. The main reason for this is size: A typical implementation of POSIX regexp takes more than 4,000 lines of code. This is bigger than all Lua standard libraries together. In comparison, the implementation of pattern matching in Lua has less than 500 lines. Of course, the pattern matching in Lua cannot do all that a full POSIX implementation does. Nevertheless, pattern matching in Lua is a powerful tool and includes some features that are difficult to match with standard POSIX implementations.

However, there are many bindings to existing regular expression libraries and also the advanced LPeg library. For a list of them with links, see http://lua-users.org/wiki/LibrariesAndBindings, chapter Text processing.

Also, see this question: Lua pattern matching vs. regular expressions


Lua regular expressions are ... abnormal. As far as I can tell from the documentation, there is no support for general alternation, nor for applying repetition operators to groups. In your case, as you say, you can get what you want with a character class (I'm not sure what the comma is doing in your character class, though).

See here: http://www.lua.org/manual/5.1/manual.html#5.4.1

(In a project I used to work on, we wrote our own Lua binding to PCRE because of this.)