使用正则表达式解析用户代理 [英] User Agent parsing with Regex

查看:82
本文介绍了使用正则表达式解析用户代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一种在线方法,用于在iPhone上查看Ruby on Rails应用程序时分离视图,它解析用户代理以检测到这种情况.我特别针对iOS 4.2+,因为以前的版本不支持我的应用程序所需的HTML5 Web套接字.

到目前为止,我正在解析/(iPhone.+OS.+4_2.+Safari)/,这似乎可以解决问题,但是我遇到的问题是,如果您使用的是Beta或更高版本的操作系统,则用户代理可能不包含4_2,但它可能支持Web套接字.

我的问题是..如何解析字符串以得到以下结果:

  • 如果大于等于4个
  • (可选?)后跟任何内容

我的正则表达式很糟糕,请原谅这个愚蠢的问题:-)

非常感谢! 汤姆.

解决方案

实际上不可能可靠地"解析用户代理字符串.几个常见的User-Agent字符串违反HTTP 1.1(我忘记了RFC编号),WRT括号之间允许使用的字符(.或/或;或其他?).当您想将某些功能列入白名单"时,User-Agent嗅探是相当脆弱的,并导致抱怨某些浏览器优先于其他浏览器(尤其是在Microsoft这样做时),这意味着有人必须保持大型正则表达式的更新. >

是否真的没有更好的方法(例如,使用JavaScript?)来检测浏览器支持的功能?

不过,您可以执行类似; *CPU +iPhone +OS +(4_(2|[3-9]|\d\d)|[5-9]|\d\d)\[0-9a-zA-Z_]* +like +Mac +OS +X *;的操作.

I found a method online for separating out views when viewing a Ruby on Rails application on an iPhone and it parses the user agent to detect this. I'm specifically targeting iOS 4.2+ since previous versions don't support HTML5 Web Sockets which I need for my application.

So far I am parsing /(iPhone.+OS.+4_2.+Safari)/ and it seems to work a treat but the problem I am having is that if you were using a beta or a future version of the OS the user agent might not include 4_2 but it may support Web Sockets.

My question is.. how could I parse the string to have the following outcome:

  • If there is a 4 or bigger
  • (Optional?) Followed by anything

My Regex is terrible, so excuse the daft question :-)

Thanks in advanced! Tom.

解决方案

It's not actually possible to "reliably" parse a user-agent string; several common User-Agent strings violate HTTP 1.1 (I forget the RFC number) WRT the characters allowed between the parentheses (. or / or ; or something?). User-Agent sniffing is pretty fragile when you want to "whitelist" certain features and leads to complaints about preferential treatment of some browsers over others (especially when it's Microsoft doing it), and means that someone has to keep giant regex updated.

Is there really no better way (e.g. with JavaScript?) to detect the features that the browser supports?

Nevertheless, you can do something like ; *CPU +iPhone +OS +(4_(2|[3-9]|\d\d)|[5-9]|\d\d)\[0-9a-zA-Z_]* +like +Mac +OS +X *;.

这篇关于使用正则表达式解析用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆