【问题标题】:Extracting an IP address from a particular string in Lua从 Lua 中的特定字符串中提取 IP 地址
【发布时间】:2018-01-01 20:19:43
【问题描述】:

我想从一个字符串中提取一个特定的值。这是我的字符串

iptables -t nat -A PREROUTING -p tcp -m tcp --dport 666 -j DNAT --to-destination 192.168.19.55

如何在 lua 中使用 string.match 从该字符串中提取192.168.19.55 ip 地址?

我完成了local ip = s:match("--to-destination (%d+.%d+.%d+.%d+)")),但我没有得到值 192.168.19.55 。我得到空值。

这有什么错误吗?有什么建议 ?

【问题讨论】:

  • 你需要使用%-转义-,这是Lua模式中的一个魔术字符。

标签: string lua lua-patterns


【解决方案1】:

使用

local s = "iptables -t nat -A PREROUTING -p tcp -m tcp --dport 666 -j DNAT --to-destination 192.168.19.55"
ip = s:match("%-%-to%-destination (%d+%.%d+%.%d+%.%d+)")
print(ip)
-- 192.168.19.55

请参阅online Lua demo

注意- 是 Lua 模式中的惰性量词,因此必须转义。此外,. 匹配任何字符,因此您也需要对其进行转义以匹配文字点。

Lua patterns Web page查看更多信息。

【讨论】:

  • 请注意,如果您确定始终是来自destination 的IP,您也可以使用s:match("%-%-to%-destination ([%d.]+)"). 内的 [...] 不必转义,[%d.]+ 匹配一个或多个数字或点。
【解决方案2】:

这也有效:

ip = s:match("destination%s+(%S+)")

它提取destination 之后的下一个单词,该单词是一系列非空白字符。

【讨论】:

  • 是的,它也适用于 IPv6。但可能最好限制可用字符的数量(例如,()-" 不应被允许)
猜你喜欢
  • 2011-02-22
  • 1970-01-01
  • 2012-12-14
  • 2022-01-27
  • 1970-01-01
  • 2013-05-25
  • 2015-12-17
  • 2015-09-19
相关资源
最近更新 更多