从 Lua 中的特定字符串中提取 IP 地址

Extracting an IP address from a particular string in Lua

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

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 。我得到空值。

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

使用

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 查看更多信息。

这也有效:

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

它提取 destination 之后的下一个词,一个 运行 非空白字符的词。