1. 程式人生 > >Lua string.gsub (s, pattern, repl [, n])

Lua string.gsub (s, pattern, repl [, n])

表示 user 參數 style ron return 類型 ble 模式

lua的string函數導出在string module中。在lua5.1,同時也作為string類型的成員方法,因此,我們既可以寫成string.gsub (s,……), 也可以s:gsub()。

string.gsub (s, pattern, repl [, n])

有四個參數,給定字符串,匹配模式、替代字符串,第四個參數是可選的,用來限制替換的範圍:表示替換次數限制。

作用就是將所有符合匹配模式的地方都替換成替代字符串。並返回替換後的字符串,以及替換次數。

其中,repl可以是string,table,或者function。

 repl如果是string,則直接替換匹配到的字符串。

 repl如果是table,則將匹配到的字符串作為key,在table內查找,取table的值來作為替換字符串。

 repl如果是function,則將每一個匹配到的字符串作為function的參數調用該函數,將函數返回的值作為新的字符串進行替換。

 如果返回的是nil或者是false,則不進行替換字符串操作。

 %1表示匹配到的字符串的第一個字符串。

 %0表示匹配到的整個字符串

例子:

    x = string.gsub("hello world", "(%w+)", "%1 %1")
     --> x="hello hello world world"
     
     x = string.gsub("hello world", "%w+", "%0 %0", 1)
     --> x="hello hello world"
     
     x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")
     --> x="world hello Lua from"
     
     x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
     --> x="home = /home/roberto, user = roberto"
     
     x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)
           return loadstring(s)()
         end)
     --> x="4+5 = 9"
local t = {name="lua", version="5.1"} x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.1.tar.gz"

Lua string.gsub (s, pattern, repl [, n])