Openresty 學習筆記(二)Nginx Lua 正則表達式相關API


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.]+(?=/)

 幫助文檔:

http://blog.csdn.net/weiyuefei/article/details/38439017


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM