【问题标题】:Derive host from the URL in LUA从 LUA 中的 URL 派生主机
【发布时间】:2018-06-30 12:16:52
【问题描述】:

我有以下网址。

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

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

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

因为它保证正确的 URL。

我设法在 rubular 上为它推导出了一些模式

但这涉及前瞻技术我如何应用前瞻技术。 像这样的

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

但是有两个问题

  • 前瞻技术不适用于 lua 匹配
  • 至少对于以下http://localhost,正则表达式不是完全证明(请注意末尾缺少斜线)

所以这是我的问题。

我该如何解决这个问题?

【问题讨论】:

  • s:match("://(.-)%f[:/%z]")
  • 不包括端口号..
  • s:match("://(.-)%f[/%z]")

标签: lua


【解决方案1】:

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

试试这个代码:

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/"

【讨论】:

  • 不包括端口号.. http://localhost:4000/path?query=foo 只返回 localhost 而我需要 localhost:4000
  • @Ratatouille,已修复。
猜你喜欢
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多