我想确定哪个设备用于我的应用程序。我想看看它是否是
即使只有几个有效选项(我们已经为所有设备安装了固定设备),我希望尽可能让它变得动态。
我在这里找到了类似的问题:Detect mobile user agent from classic ASP and redirect on session start
我熟练并编写了以下函数,以检查当前访问我网站的设备。但是,我认为它有点混乱,因为它是如此"静态"谈到正则表达式
这就是我提出的:
public function checkUserAgent()
Set Regex = New RegExp
With Regex
.Pattern = "(Mobile\sSafari|Linux;\sAndroid)"
.IgnoreCase = True
.Global = True
End With
Match = Regex.test(Request.ServerVariables("HTTP_USER_AGENT"))
If Match then
user_agent = "Phone"
End If
Set Regex = New RegExp
With Regex
.Pattern = "(windows\sNT)"
.IgnoreCase = True
.Global = True
End With
Match = Regex.test(Request.ServerVariables("HTTP_USER_AGENT"))
If Match then
user_agent = "PC"
End If
Set Regex = New RegExp
With Regex
.Pattern = "(ipad)"
.IgnoreCase = True
.Global = True
End With
Match = Regex.test(Request.ServerVariables("HTTP_USER_AGENT"))
If Match then
user_agent = "Tablet"
End If
end function
我现在的问题:看起来RegExp的代码是多余的。我该如何改进?我怎么可能使这个更紧凑,结果相同?我需要获得用户代理类型,因此我可以更新我的数据库并继续计算,使用了多少设备/类型。
答案 0 :(得分:1)
我会更像这样构造它。
dim device
device = checkUserAgent
response.write device
function checkUserAgent()
dim user_agent
user_agent = Request.ServerVariables("HTTP_USER_AGENT")
if reTest(user_agent, "(Mobile\sSafari|Linux;\sAndroid)") then
checkUserAgent = "Phone"
elseif reTest(user_agent, "(windows\sNT)") then
checkUserAgent = "PC"
elseif reTest(user_agent, "(ipad)") then
checkUserAgent = "Tablet"
end if
end function
function reTest(subject, pattern)
dim re, returnVal
returnVal = false
Set re = New RegExp
With re
.Pattern = pattern
.IgnoreCase = True
.Global = True
End With
If re.test(subject) then
returnVal = true
End If
Set re = Nothing
reTest = returnVal
end function
或者,如果您对设备类型进行更细化并最终获得更多其他类型,则使用字典管理可能更容易。在这种情况下,checkUserAgent可能看起来更像:
function checkUserAgent()
dim user_agent, d
user_agent = Request.ServerVariables("HTTP_USER_AGENT")
set d = Server.CreateObject("Scripting.Dictionary")
d.add "Phone", "(Mobile\sSafari|Linux;\sAndroid)"
d.add "PC", "(windows\sNT)"
d.add "Tablet", "(ipad)"
for each k in d.keys
if (reTest(user_agent, d.item(k))) then
checkUserAgent = k
exit for
end if
next
end function