ngx.re.match
语法: captures, err = ngx.re.match(subject, regex, options?, ctx?, res_table?)
环境: init_worker_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, ssl_session_store_by_lua*
官方的DEMO
local m, err = ngx.re.match("hello, 1234", "[0-9]+") if m then
-- m[0] == "1234"
else
if err then ngx.log(ngx.ERR, "error: ", err) return
end ngx.say("match not found") end
从URL地址中获取域名,脚本:ngx-re-match.lua
local m, err = ngx.re.match("http://www.tinywan.com/live", "(?<=://)[A-Za-z0-9.]+(?=/)") if m then
-- m[0] == "1234"
ngx.say(m[0]) ngx.say(m[1]) else
if err then ngx.log(ngx.ERR, "error: ", err) return
end ngx.say("match not found") end ngx.say('finished')
虚拟主机:
server { listen 8334; server_name 127.0.0.1; resolver 8.8.8.8; location /ngx_re_match { lua_code_cache off; content_by_lua_file $path/lua/ngx-re-match.lua; } }
curl 请求结果:
curl http://127.0.0.1:8334/ngx_re_match
www.tinywan.com nil finished
如果想获取一级域名:tinywan.com 请使用表达式:
(?<=://w{5}.)[A-Za-z0-9.]+(?=/)
帮助文档: