## **正则测试用例:** ~~~ --re. find , re. gsub , re. match , re. gmatch 可用。这些函数具有与 Lua 模式匹配相同的 API -- 重定义assert函数 local assert = function(a, b) if a == true then print('true') return end print(a) if b then print(b) end end local re = woo.re local a, b, i, s, t -- quote assert(re.quote("^$.?a")) --== [[\^\$\.\?a]] -- find function f(s, p) local i, e = string.find(s, p) if i then return string.sub(s, i, e) end end a, b = re.find('', '') assert(a, b) a, b = re.find("abcd efgh ijk", "cd e", 1, true) assert(a, b) a, b = re.find("abcd efgh ijk", "cd e", -1, true) assert(a) assert(not pcall(re.find, "aaa", "(aaaa")) assert(re.find("aaaa", "(b|c)*")) a, b, s = re.find("abcd efgh ijk", "i([jk])") assert('abs:' .. a .. '+' .. b .. '+' .. s) -- gsub assert(not pcall(re.gsub, "aaa", "(aaaa", "${1}")) s, a = re.gsub("aaaa", "bbbb", "") assert(s, a) assert(re.gsub("hello world", [[(\w+)]], "${1} ${1}")) t = { name = "lua", version = "5.1" } assert(re.gsub("$name-$version.tar.gz", [[\$(\w+)]], t)) assert(re.gsub("name version", [[\w+]], t)) assert(re.gsub("4+5 = $return 4+5$", "\\$(.*)\\$", function(s) return loadstring(s)() end) == "4+5 = 9") assert(re.gsub("$ world", "\\w+", string.upper)) -- gmatch assert(not pcall(re.gmatch, "hello world", "(aaaaa")) i = 1 for w in re.gmatch("hello world", "\\w+") do if i == 1 then assert('gmatch1:' .. w) elseif i == 2 then assert('gmatch2' .. w) end i = i + 1 end assert('final i=' .. i) i = 1 for k, v in re.gmatch("from=world, to=Lua", "(\\w+)=(\\w+)") do if i == 1 then assert(k == "from" and v == "world") elseif i == 2 then assert(k == "to" and v == "Lua") end i = i + 1 end assert(i == 3) -- match assert(not pcall(re.match, "hello world", "(aaaaa")) assert(re.match("$$$ hello", "z") == nil) assert(re.match("$$$ hello", "\\w+") == "hello") assert(re.match("hello world", "\\w+", 6) == "world") assert(re.match("hello world", "\\w+", -5) == "world") a, b = re.match("from=world", "(\\w+)=(\\w+)") assert(a == "from" and b == "world") for k, v in woo.re.gmatch("from=world, to=Lua", "(\\w+)=(\\w+)") do print(k,v) end ~~~ ## **输出:** \^\$\.\?a 1 0 3 6 nil true nil abs:11+12+j true aaaa 0 hello hello world world 2 lua-5.1.tar.gz 2 lua 5.1 2 true $ WORLD 1 true gmatch1:hello gmatch2world final i=3 true true true true true true true true true from world to Lua