http://lua-users.org/wiki/StringLibraryTutorial
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
string.gsub(s, pattern, replace [, n]) s:gsub(pattern, replace [,n]) This is a very powerful function and can be used in multiple ways. Used simply it can replace all instances of the pattern provided with the replacement. A pair of values is returned, the modified string and the number of substitutions made. The optional fourth argument n can be used to limit the number of substitutions made: > = string.gsub("Hello banana", "banana", "Lua user") Hello Lua user 1 > = string.gsub("banana", "a", "A", 2) -- limit substitutions made to 2 bAnAna 2 Just like string.find() we can use patterns to search in strings. Patterns are covered in the PatternsTutorial. If a capture is used this can be referenced in the replacement string using the notation %capture_index, e.g., > = string.gsub("banana", "(an)", "%1-") -- capture any occurences of "an" and replace ban-an-a 2 > = string.gsub("banana", "a(n)", "a(%1)") -- brackets around n's which follow a's ba(n)a(n)a 2 > = string.gsub("banana", "(a)(n)", "%2%1") -- reverse any "an"s bnanaa 2 If the replacement is a function, not a string, the arguments passed to the function are any captures that are made. If the function returns a string, the value returned is substituted back into the string. > = string.gsub("Hello Lua user", "(%w+)", print) -- print any words found Hello Lua user 3 > = string.gsub("Hello Lua user", "(%w+)", function(w) return string.len(w) end) -- replace with lengths 5 3 4 3 > = string.gsub("banana", "(a)", string.upper) -- make all "a"s found uppercase bAnAnA 3 > = string.gsub("banana", "(a)(n)", function(a,b) return b..a end) -- reverse any "an"s bnanaa 2 Pattern capture: The most commonly seen pattern capture instances could be "(.-)", e.g. "{(.-)}" means capture any characters between the curly braces {} (lazy match, i.e. as few characters as possible) "(.*)", e.g. "{(.*)}" means capture any characters between the curly braces {} (greedy match, i.e. as many characters as possible) > = string.gsub("The big {brown} fox jumped {over} the lazy {dog}.","{(.-)}", function(a) print(a) end ) brown over dog > = string.gsub("The big {brown} fox jumped {over} the lazy {dog}.","{(.*)}", function(a) print(a) end ) brown} fox jumped {over} the lazy {dog |