【问题标题】:Check for valid domain检查有效域
【发布时间】:2014-08-12 05:11:32
【问题描述】:

我想在这个功能中加入域检查:

GetType = function(ip)
 local Split = function(s,sep)
  local t={};i=1
  for str in string.gmatch(s,"([^"..sep.."]+)") do
   t[i] = str
   i = i + 1
  end
  return t
 end
 local R = {ERROR=0,IPV4=1,IPV6=2,DOMAIN=3,STRING=4}
 if type(ip) ~= "string" then return R.ERROR end
 local chunks = {ip:match("(%d+)%.(%d+)%.(%d+)%.(%d+)")}
 if #chunks == 4 then
  for _,v in pairs(chunks) do
   if tonumber(v) > 255 then return R.STRING end
  end
  return R.IPV4
 end
 local chunks = {ip:match(("([a-fA-F0-9]*):"):rep(8):gsub(":$","$"))}
 if #chunks == 8 then
  for _,v in pairs(chunks) do
   if #v > 0 and tonumber(v, 16) > 65535 then return R.STRING end
  end
  return R.IPV6
 end
 -- Domain check
 -- Ensuring only alphanumeric characters and . and -
 -- Ensuring no --
 -- Ensuring - is not at the start or end of part
 -- Ensuring there is more than one part
 if string.gsub(ip,"[%w%-%.]","") ~= "" then return R.STRING end
 if string.find(ip,'--',1,true) ~= nil then return R.STRING end
 local t = Split(ip,"%.")
 if #t <= 1 then return R.STRING end
 for i,v in pairs(t) do
  if string.find(t[i],'-',1,true) == 1 or string.find(t[i],'-',#t[i],true) ~= nil then return R.STRING end
 end
 return R.DOMAIN
end

它在 IPV4/6 上做得很好,但我对如何进行域检查有点迷茫,所以问题是:

检查的最佳方法是什么?

我是否已检查所有内容是否正确?

【问题讨论】:

    标签: string lua string-matching lua-patterns lua-5.1


    【解决方案1】:

    我不确定你描述的要求是否正确,但这个逻辑符合你的要求:

    -- Only characters A-Z and numbers 0-9 and the - so long as it's not at the start or end of string.
    -- Be at least 3 characters excluding the extension.
    -- No spaces allowed (wont be any in the string anyway).
    -- Have an extension with at least 2 characters.
    local domain, ext = ip:match("([A-Z0-9][A-Z0-9%-]+[A-Z0-9])%.([A-Z0-9][A-Z0-9]+)")
    if not domain or not ext then return R.STRING end
    -- Hyphen can't be used in consecutive positions.
    if domain:match '--' then return R.STRING end
    -- Be 63 characters max excluding the extension.
    if #domain > 63 then return R.STRING end
    -- return R.DOMAIN if domain
    return R.DOMAIN
    

    显然,您可以将所有三个条件组合在一起:

    return domain and ext and not domain:match('--') and #domain <= 63
    and R.DOMAIN or R.STRING
    

    【讨论】:

    • 谢谢 Paul,你知道我认为这种模式很混乱,因为有时域扩展名可能有几个 .,例如:.co.uk,我已经更改了功能,所以只有域名本身正在被检查,但在那之后我似乎无法使模式正常运行。
    • 如果要处理多个扩展,需要在扩展中允许.。您可能还需要通过添加^ 作为第一个字符来将模式锚定在字符串的开头。您显然需要对扩展进行额外检查,以确保它符合您的规则。
    猜你喜欢
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多