Search code examples
c#iphoneiosregexmobile-safari

Generic regex to get iOS version, all iOS devices


I am trying to find a regex that gets the iOS version from all the iOS devices. I can't do one seperately for each device type (iphone, ipad, ipod), I need a generic one.

Before I do the match, I check if it is a valid iOS device. The solution I have come up with is:

Match match = Regex.Match(HttpContext.Current.Request.UserAgent, @"(?<version>\d+(_\d+)+) like Mac OS X");
string versionNr = match.Groups["version"].ToString().Replace("_", ".");

I have checked quite a few devices agent strings, and so far they all match. But I am a bit worried that it wont match all, and just checking if anyone has a better regex.

Thanks in advance.


Solution

  • As mentioned in other answers, regex is not 100% reliable for testing user agent strings, but to answer the question how about this:

    (i[PSa-z\s]+);.*?CPU\s([OSPa-z\s]+(?:([\d_]+)|;))
    

    The first match group is the type iPhone/pad/pod and the second group is the IOS version (except for IOS 1 where no version number is present)

    The corpus used may be missing some of the user agents, but you can fiddle with it.