当前位置: 代码迷 >> 综合 >> lua——string之string.gsub
  详细解决方案

lua——string之string.gsub

热度:78   发布时间:2024-02-28 13:43:58.0

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"
  相关解决方案