Get Android OS version from user-agent

前端 未结 5 771
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 11:21

I\'ve been trying to find a parser or regex that will give me the Android OS version from a user agent string.

E.g.

Mozilla/5.0 (Linux; U; Android 2.         


        
相关标签:
5条回答
  • 2020-12-08 11:52

    Regex should work, something along the untested lines of

    Android ([0-9]\.[0-9](\.[0-9])?);

    And then use whatever regex function you use to get that part inside the parens.

    0 讨论(0)
  • 2020-12-08 11:56

    If you want to use it with User-Agent it might be safe but else you shouldn't use it.

    Android ((\d+|\.)+[^,;]+)
    

    It catches everything after Android it works with,

    1.6 2.4.4 10.12.5

    To test with Live Regex: https://www.phpliveregex.com/p/uPw

    0 讨论(0)
  • 2020-12-08 12:06

    May I present an answer that others can easily copy and paste.

    navigator.userAgent.match(/Android [\d+\.]{3,5}/)[0].replace('Android ','')
    
    0 讨论(0)
  • 2020-12-08 12:08

    Motorola's player user agents can have the following:

    Linux;Android ; Release/4.1.2
    

    So, I've had to start using the the following:

    [a|A]ndroid[^\d]*([\d[_|.]]+\d)
    
    0 讨论(0)
  • 2020-12-08 12:11

    This regular expression is a bit more "future proof" than mathepic's answer:

    Android (\d+(?:\.\d+)*);
    

    It allows for multiple digits in each place as well as additional periods in the version number. Android's been out 3 years and we're on 3.0. Eventually we'll get to 10.0.0.

    This will catch all of the following:

    • 1.6 (real)
    • 2.3.4 (real)
    • 9
    • 12.34.56 (fake. but one day...)
    • 3.4.5.6 and 4.5.6.7.8.9 (fake... but just in case)

    This could be written a little more strictly as:

    Android (\d+(?:\.\d+){0,2});
    

    This sticks more closely to the schema we've already seen used, but could potentially miss some versions of they decide to add an additional .1 at the end of a version. It also matches for the future 10.0.0 version.

    0 讨论(0)
提交回复
热议问题