从 URL 中获取主机地址(Lua 版)

我有以下 URL。

http://localhost:4000/path?query=foo
http://localhost:4000/
http://localhost
http://localhost/

我只想返回 host 部分。老实说,像这样的 URL 我并不关心

 http://localhost:abcd/
 http://localhost:abcd/path?query=foo

因为它们肯定是正确的 URL。

我在 rubular 上找到了一些规律

但这涉及到预读技术,我该如何应用预读技术。 看起来像这样

^https?:\/\/(.+)(?=[\/|$])

但是有 2 个问题

  • 预读技术不能与 lua 匹配工作
  • 正则表达式并不完备,至少对于以下 URL http://localhost(注意末尾斜杠的缺失)

所以我的问题是

我该如何解决?

点赞
用户107090
用户107090

模式匹配的关键在于避免特殊情况,例如可选分隔符。将 / 添加到字符串中可简化任务。

尝试下面的代码:

function host(s)
    return (s.."/"):match("://(.-)/")
end

function test(s)
    print(s,host(s))
end

test"http://localhost:4000/path?query=foo"
test"http://localhost:4000/"
test"http://localhost"
test"http://localhost/"
2018-06-29 16:29:17