【问题标题】:Select only part of the string with regex使用正则表达式仅选择部分字符串
【发布时间】:2018-07-22 19:12:21
【问题描述】:

我有 2 个字符串:

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

我只想为第一个保留$ip = 127.0.0.1,为第二个保留$port = 80。我应该如何使用正则表达式?

/////////更新//////////

我这样做了,它有效,但写得不好:

   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);

【问题讨论】:

  • 我对nginx一无所知,但我会用正则表达式replace_filter '[[\]{}"]' '' g;替换
  • @Leyffda 我更新了我的帖子。如果您有更好地重写的想法,我很感兴趣。
  • _, _, ip2 = string.find(ip, '"ip":"([^"]+)') 怎么样?
  • 两个字符串的一个解决方案:s:match('"([%d.]+)"')
  • $ip = 是字符串的一部分吗?

标签: regex nginx lua


【解决方案1】:

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

Online demo

但如果您只想获取另一个字符并删除它们,请使用(?:([\[\]\{\}\":]+)|(ip")|(port")|\s{2,})

demo

【讨论】:

  • 谢谢,写得更好
【解决方案2】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-29
    • 2021-05-16
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    相关资源
    最近更新 更多