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.
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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With