OpenResty 中的正则匹配和替换

OpenResty Lua 正则表达式 About 2,100 words

正则匹配

ngx.re.match

匹配第一次出现的。未匹配到返回nil,匹配到了返回一个table对象。table[0]中是整个匹配到的字符串,table[1]中是左边开始第一个的圆括号()匹配到的字符串,table[2]中是左边开始第二个圆括号()匹配到的字符串,以此类推。

ngx.re.find

ngx.re.match类似,但是只返回from开始索引位置和to结束索引位置,如果没匹配到则fromtonil

ngx.re.gmatch

ngx.re.match类似,返回一个Lua可迭代对象,包含所有匹配到的字符串。

文档地址:https://github.com/openresty/lua-nginx-module#ngxrematch

正则替换

ngx.re.sub

替换第一个匹配到的字符串。

ngx.re.gsub

替换所有匹配到的字符串。

文档地址:https://github.com/openresty/lua-nginx-module#ngxresub

示例代码

ngx.re.match

m[0]是匹配到的整个字符串,m[1]([0-9])匹配到的字符串。

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

     ngx.say("match not found")
 end

ngx.re.find

fromto索引位置,string.sub()方法截取字符串。

local s = "hello, 1234"
 local from, to, err = ngx.re.find(s, "([0-9]+)")
 if from then
     ngx.say("from: ", from)
     ngx.say("to: ", to)
     ngx.say("matched: ", string.sub(s, from, to))
 else
     if err then
         ngx.say("error: ", err)
         return
     end
     ngx.say("not matched!")
 end

ngx.re.gmatch

循环迭代获取匹配到的字符串。

local it, err = ngx.re.gmatch("hello, world!", "([a-z]+)", "i") -- 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(m[0])
    ngx.say(m[1])
end

ngx.re.sub

$0$1是取匹配到的字符串,也可以使用${0}${1}来取匹配到的字符串。需要替换为$符号,则可以传入$$

将第一个匹配到的数字1,替换为匹配到的字符串和00

local newstr, n, err = ngx.re.sub("hello, 1234", "([0-9])[0-9]", "[$0][$1]")
if newstr then
    -- newstr == "hello, [12][1]34"
    -- n == 1
else
    ngx.log(ngx.ERR, "error: ", err)
    return
end

local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "${0}00")
    -- newstr == "hello, 100234"
    -- n == 1

local newstr, n, err = ngx.re.sub("hello, 1234", "[0-9]", "$$")
    -- newstr == "hello, $234"
    -- n == 1

开源案例

https://github.com/fendoudebb/z-blog-openresty

Views: 8,188 · Posted: 2020-03-12

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh