Lua string replacement function string. gsub (S, Pat, REPL [, N])
Link: http://blog.csdn.net/zhangxaochen/article/details/8085484
Function prototype string. gsub (S, Pat, REPL [, N])
This is what global means to replace the substring globally.
S: Source string
Pat: pattern, matching mode
Repl: replacement, replace the string matched by Pat with repl
[, N]: optional, indicating that only the first n characters of the source string are viewed.
For example, write a trim function:
Function trim (s) Return (string. gsub (S, "^ % S *(. -) % S * $ "," % 1 ") end ---- then call: S = '\ t a BC d' print (TRIM (s) ----- output: a bc d, starts with \ t, and spaces at the end are all truncated by trim
Here are some explanations:
1. Return (string. gsub (...). Note that there is a bracket outside string. gsub. In fact, two values are returned after gsub is called. One is the replaced string, and the other is the number of replacement times. Once parentheses are added, only the first value is returned, that is, the replaced string. You can try to remove the outer parentheses to see what is output
2. The matching mode string "^... $" indicates that the entire string is matched. ^ Starts with a table, and $ indicates the end. Here, the effect of (.-) is the same as that of (. *), because it matches from the beginning of the string to the end.
If ^ and $ are removed, the entire string is not matched. Under the action of (.-), the output is: ABCD.
Link: http://blog.csdn.net/zhangxaochen/article/details/8085484
{Over }}