zoukankan      html  css  js  c++  java
  • Lua string.gsub (s, pattern, repl [, n])

    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"
  • 相关阅读:
    ASP.NET MVC案例教程(一)
    大型网站架构演变和知识体系
    Windows下的.NET+ Memcached安装
    ASP.NET MVC案例教程(基于ASP.NET MVC beta)
    JS调用webservice的通用函数。
    ASP.NET MVC案例教程(基于ASP.NET MVC beta)——第五篇:MVC整合Ajax
    自己实现memcached客户端库
    ASP.NET 2.0防止同一用户同时登陆
    cookie,dom,css,js实现页面换肤
    在线编辑器实现原理(兼容IE和FireFox)
  • 原文地址:https://www.cnblogs.com/slysky/p/7327031.html
Copyright © 2011-2022 走看看