SoFunction
Updated on 2025-04-13

Share 5 code snippets of Lua operation string

1. Match numbers, letters and underscores in strings

Copy the codeThe code is as follows:

str = "hello_+asdf2312+887441a+asdf"
table = {}
(str, "([%w_]+)",

function(w)

(table,w)

end
end

2. Replace the specified character in the string

Copy the codeThe code is as follows:

str = "hello,john"
s = (str, "john", "james")
s ==>"hello,james"

3. Determine whether there is a target string in the string

Copy the codeThe code is as follows:

str = "hello,john"
start, end = (str, "hello")
start ==>1
end ==>5

4. Get the file name from the absolute path of the file

Copy the codeThe code is as follows:

fn_flag = (filename, "\\")

if fn_flag then

dest_filename = (filename, ".+\\([^\\]*%.%w+)$")
end

fn_flag = (filename, "/")

if fn_flag then

dest_filename = (filename, ".+/([^/]*%.%w+)$")
end

5. Remove the contents in brackets in the string and remove the ending spaces

Copy the codeThe code is as follows:

str = " helloa,ni hao (asdfasdf) "
newstr = (str,"%b()","")

newstr = (newstr, "^%s*(.-)%s*$", "%1")

print(newstr)---->helloa,ni hao