【问题标题】:Lua - Using string.find to find a sentence?Lua - 使用 string.find 查找句子?
【发布时间】:2021-11-02 19:37:07
【问题描述】:

在之前的堆栈溢出响应之后,(here) 我正在尝试检查在我正在运行的 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 ("Pings were all successfull.")
    else
        print ("Pings were all unsuccessfull.")
    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
     
Pings were all unsuccessfull.     

我做错了什么,因为它没有看到“0% 丢包”并说它成功了?

【问题讨论】:

  • 不是read("*all")吗?

标签: lua


【解决方案1】:

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

但是,此模式也将匹配 100% packet loss。我建议", 0%% packet loss"

此外,它不适用于在报告中显示小数的 macOS:0.0% packet loss

【讨论】:

  • 谢谢@lhf 做到了……
猜你喜欢
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 2011-03-12
  • 2017-03-01
  • 2014-08-04
  • 2016-02-13
相关资源
最近更新 更多