OpenResty 中的正则匹配和替换
OpenResty Lua 正则表达式 大约 2100 字正则匹配
ngx.re.match
匹配第一次出现的。未匹配到返回nil
,匹配到了返回一个table
对象。table[0]
中是整个匹配到的字符串,table[1]
中是左边开始第一个的圆括号()
匹配到的字符串,table[2]
中是左边开始第二个圆括号()
匹配到的字符串,以此类推。
ngx.re.find
与ngx.re.match
类似,但是只返回from
开始索引位置和to
结束索引位置,如果没匹配到则from
、to
为nil
。
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
from
、to
索引位置,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
开源案例
阅读 7553 · 发布于 2020-03-12
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Redis 执行 Lua 脚本抛出 StatusOutput does not support set(long) 异常阅读 9176
-
Redis 使用 hotkeys 查看热点数据阅读 5102
-
Spring Boot Thymeleaf 国际化 i18n阅读 115
-
MySQL-Utilities 工具报 TypeError: wrap_socket() got an unexpected keyword argument 'ciphers'阅读 3441
-
Linux 使用 dstat 性能监测阅读 2563
-
微信小程序修改 wxParse 支持代码块不换行/表格无法横向滚动等阅读 3904
-
走进 Rust:Crate、模板阅读 2480
-
Java 并发编程之 AtomicInteger AtomicLong阅读 1278
-
Windows 查看是否是固态硬盘阅读 1886
-
OpenResty 使用 cjson 操作 JSON 数据阅读 6756