使用正则表达式

时间:2018-02-12 15:08:32

标签: regex nginx lua

我有2个字符串:

$ip =        [{"ip":"127.0.0.1"}]
$port =      [{"port":"80"}]

我希望第一个只保留$ip = 127.0.0.1,第二个保留$port = 80。我该如何处理正则表达式?

////////// UPDATE //////////

我这样做并且有效,但写得不好:

   ip = string.match(respIp.body, "%:(.*)");
   ip = string.match(ip, "(.*)%}");
   ip = string.sub(ip, 2, string.len(ip)-1);

   port = string.match(respPort.body, "%:(.*)");
   port = string.match(port, "(.*)%}");
   port = string.sub(port, 2, string.len(port)-1);

2 个答案:

答案 0 :(得分:1)

您可以使用/([$]ip =).+(?<=:")([\d.]+)/g然后获取第1组和第2组

Online demo

但是如果你想获得另一个角色并删除它们,请使用(?:([\[\]\{\}\":]+)|(ip")|(port")|\s{2,})

demo

答案 1 :(得分:0)

ip - 匹配任何ip4格式的字符串, port - 匹配双引号之间的任何十进制字符

local bodyIp   = '$ip =        [{"ip":"127.0.0.1"}] '
local bodyPort = '$port =      [{"port":"80"}] '


local ip = bodyIp:match('(%d+%.%d+%.%d+%.%d+)') -- any ip
local port = bodyPort:match(':"(%d+)"') --  

print(ip,port)
相关问题