Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting iOS Version Number from User Agent using Regular Expressions

Tags:

regex

version

ios

If I have an iOS user-agent like

Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7

or

Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/7D11

How would I detect the iOS version using regular expressions so that it would return e.g.

4.0

for the above user agent?

like image 826
user1477182 Avatar asked Jun 23 '12 18:06

user1477182


1 Answers

The RegEx that is working for me is:

/OS ((\d+_?){2,3})\s/

An iPad 5.1.1 has an HTTP_USER_AGENT like this:

"Mozilla/5.0 (iPad; CPU OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3"

So 3 numbers in the iOS version and not iPhone OS present.

A possible Ruby implementation could be:

def version_from_user_agent(user_agent)
  version = user_agent.match(/OS ((\d+_?){2,3})\s/)
  version = version[1].gsub("_",".") if version && version[1]
end

It returns nil if not iOS version found

like image 157
fguillen Avatar answered Oct 04 '22 06:10

fguillen