resty 正则

local m, err = ngx.re.match("hello, 1234", "[0-9]+")
if m then
  ngx.say("match,m[0]:",m[0])
  ngx.say("match,m[1]:",m[1])
else
  if err then
    ngx.log(ngx.ERR, "error: ", err)
    return
  end
  ngx.say("match not found")
end

--返回一个 Lua 迭代器
local it, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i")
if not it then
  ngx.log(ngx.ERR, "error: ", err)
  return
end

while true do
  local m, err = it()
  if err then
    ngx.log(ngx.ERR, "error: ", err)
    return
  end
  if not m then
    -- no match found (any more)
    break
  end
  -- found a match
  ngx.say("gmatch.m[0]:",m[0])
  ngx.say("gmatch.m[1]:",m[1])
end
 
--find函数并不创建任何新 Lua 字符串或 Lua 表,运行速度大大快于 ngx.re.match。所以如果可能请尽量使用本函数 
local s = "dfsfs111fds"
local from, to, err = ngx.re.find(s, "([0-9]+)", "jo")--j:启用 PCRE JIT 编译,o:仅编译一次模式 (类似 Perl 的 /o 修饰符),启用 worker 进程级正则表达式编译缓存
if from then
  ngx.say("find pos:", from,"-",to)
  ngx.say("matched:", string.sub(s, from, to))
else
  if err then
    ngx.say("error: ", err)
    return
  end
  ngx.say("not matched!")
end

match,m[0]:1234
match,m[1]:nil
gmatch.m[0]:hello
gmatch.m[1]:hello
gmatch.m[0]:world
gmatch.m[1]:world
find pos:6-8
matched:111

猜你喜欢

转载自xiangjie88.iteye.com/blog/2382793