Skip to content

string.Split and string.SafePattern - #35

Open
vugi99 wants to merge 3 commits into
nanos-world:masterfrom
vugi99:stringsplit
Open

string.Split and string.SafePattern#35
vugi99 wants to merge 3 commits into
nanos-world:masterfrom
vugi99:stringsplit

Conversation

@vugi99

@vugi99 vugi99 commented May 24, 2026

Copy link
Copy Markdown
Contributor

It's annoying to copy the same code over and over to split strings. (Plus some of my versions in my packages had bugs or limitations)

-- Makes a safe string to append in a pattern without triggering special lua pattern rules
function string.SafePattern(str)

--[[
Splits strings, using a simple delimiter or a pattern delimiter
]]--
function string.Split(str, delimiter, is_pattern)

Comment thread string.lua Outdated
Comment thread string.lua Outdated
vugi99 and others added 2 commits July 18, 2026 16:03
Co-authored-by: Neo <Cheatoid@users.noreply.github.com>
@vugi99

vugi99 commented Jul 19, 2026

Copy link
Copy Markdown
Contributor Author

@gtnardy what do you think ?

@gtnardy

gtnardy commented Jul 20, 2026

Copy link
Copy Markdown
Member

what are the use cases for the is_pattern ans SafePattern method?

@vugi99

vugi99 commented Jul 20, 2026

Copy link
Copy Markdown
Contributor Author

is_pattern allow you to split strings using a lua pattern : Split newlines : "([^\r\n]+)"
SafePattern : could be used for a user search query, escape the special pattern characters to find what the user wants without lua patterns intervention. Eg : user wants to search for [DEBUG] logs in a string, this won't work if this is entered as the [ character is a lua pattern character, it has to be escaped first with %.

@gtnardy

gtnardy commented Jul 20, 2026

Copy link
Copy Markdown
Member

I see, I found it confusing for someone that doesn't know what it does, and the difference for the methods

Comment thread string.lua
}

function string.SafePattern(str)
return (string.gsub(str, ".", escaped_pattern_characters))

@Cheatoid Cheatoid Jul 21, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth benchmarking on Lua 5.4.8:
return (string.gsub(str, "([%(%)%[%]%.%%%+%-%*%?%^%$])", "%%%1"))

There is a trade off:

  • This excludes NUL char \0, which Lua patterns cannot conveniently match inside a character class. But, it could be handled with an additional string.gsub call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants