lua——string之string.gsub


translated from the lua document

string.gsub用法:

函數原型:string.gsub( s, pattern, rep1[, n] )
函數功能:返回一個和pattern匹配,並且用rep1替換的副本。rep1可以是string、table和functin。
                  第二個返回值n是代表匹配的個數。
 
rep1說明:
如果rep1是string類型,那么rep1用於替換匹配的字符串。%代表轉義字符,rep1中%n里面,
n的范圍是1~9,代表第n個捕獲的子串(看下面的例子)。%0代表所有的匹配,%%代表單個%。
 
如果rep1是表,設表為t,則匹配的項會用t[match]來代替,match是匹配的項。如果沒有匹配,
則原串返回。
 
如果rep1是函數,那么,所有匹配的子串會分別作為函數的參數,如果匹配n次,則調用函數n次。
 
如果表或者函數的返回值是string或者number,那么它會替換匹配的子串;
如果返回值是false或者nil,那么不會作任務替換返回值是和原來的string一樣。
 

下面是一些例子:

     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"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM