Lua - 使用string.find查找句子?

作为之前在Stack Overflow上的回答的跟进 ( 这里),我正在尝试检查 io.popen 命令的响应中是否返回了特定的句子/字符串。

local function DevicePing(ip)
    local handler = io.popen("ping -c 3 " ..ip.. " 2>&1")
    local response = handler:read("*a")
    print(response)
    if string.find(response, "0% packet loss") then
        print ("Ping都成功了。")
    else
        print ("Ping都失败了。")
    end
end

DevicePing("192.168.1.180")

但无论我运行多少次,都不能找到请求的字符串/句子;请参见下面的打印输出。

PING 192.168.1.180 (192.168.1.180): 56 data bytes
64 bytes from 192.168.1.180: seq=0 ttl=64 time=2.983 ms
64 bytes from 192.168.1.180: seq=1 ttl=64 time=1.620 ms
64 bytes from 192.168.1.180: seq=2 ttl=64 time=2.465 ms

--- 192.168.1.180 ping statistics ---
3 packets transmitted, 3 packets received, 0% packet loss
round-trip min/avg/max = 1.620/2.356/2.983 ms

Ping都失败了。

我做错了什么,以至于它不会看到‘0% packet loss‘存在并说它是成功的?

原文链接 https://stackoverflow.com/questions/69062239

点赞
stackoverflow用户107090
stackoverflow用户107090

% 是 Lua 模式中的转义字符。使用 "0%% packet loss" 表示字面意义上的 %

然而,这个模式也会匹配 100% packet loss。建议使用 ", 0%% packet loss"

此外,在显示小数的 macOS 中,这种模式无法正常工作:0.0% packet loss

2021-09-05 10:53:28