| |
| |
| |
|
|
| local util = require 'extensions-lite.core.util' |
| local stringex = {} |
|
|
| local patternescape = function(str) |
| return str:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%1") |
| end |
|
|
| function stringex.split(str, delim, plain) |
| util.checkType("string", str, "string", delim) |
| |
| |
| local tokens, pos, plain = {}, 1, not (plain == false) |
| repeat |
| local npos, epos = string.find(str, delim, pos, plain) |
| table.insert(tokens, string.sub(str, pos, npos and npos - 1)) |
| pos = epos and epos + 1 |
| until not pos |
| return tokens |
| end |
|
|
| function stringex.trim(str, chars) |
| util.checkType("string", str) |
| if not chars then |
| return str:match("^[%s]*(.-)[%s]*$") |
| end |
| local chars = patternescape(chars) |
| return str:match("^[" .. chars .. "]*(.-)[" .. chars .. "]*$") |
| end |
|
|
| function stringex.contains(str, substr) |
| util.checkType("string", str, "string", substr) |
| return string.find(str, substr, 1, true) ~= nil |
| end |
|
|
| function stringex.rfind(str, pattern, offset, plain) |
| util.checkType("string", str, "string", pattern) |
| local pos, lnpos, lepos, plain = offset and offset - 1 or 0, offset or 1, -1, not (plain == false) |
| repeat |
| local npos, epos = string.find(str, pattern, pos, plain) |
| pos = epos and epos + 1 |
| if pos then |
| lnpos, lepos = npos, epos |
| end |
| until not pos |
| return lnpos, lepos |
| end |
|
|
| return stringex |
|
|