Logical 'or' in Lua patterns?

Yuri Ghensev picture Yuri Ghensev · Aug 11, 2010 · Viewed 11.8k times · Source

Is it possible to achieve in Lua?

local noSlashEnding = string.gsub("slash\\ending\\string\\", "\\|/$", "")
-- noSlashEnding should contain "slash\\ending\\string"

local noSlashEnding2 = string.gsub("slash/ending/string/", "\\|/$", "")
-- noSlashEnding2 should contain "slash/ending/string"

The point here is the no acceptance of logical 'or' statements in Lua patterns.


EDIT: Just realized that is possible by doing this:

strng.gsub("slash\\ending\\string\\", "[\\/]$", "")

Although logical 'or' for patterns is still missing.

Answer

Michal Kottman picture Michal Kottman · Aug 13, 2010

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