User Agent parsing with Regex
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 f开发者_运维技巧or 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 *;
.
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.
([5-9]|\d\d)[^+]*
精彩评论