User Agent parsing with Regex

半世苍凉 提交于 2019-12-09 21:56:01

问题


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.


回答1:


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 *;.




回答2:


While this technically could be done, you would have to list all the possible future version numbers explicitly. regex is a text matching tool; there's no easy way to include logic such as "return true if the number is greater than this, false if smaller". You would probably want to just extract the number string ([0-9]+_[0-9]+ or something) and then do the logic on the output of that.




回答3:


([5-9]|\d\d)[^+]*



来源:https://stackoverflow.com/questions/4259973/user-agent-parsing-with-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!