RegEx: Match Android device name with JavaScript

1.8k views Asked by At

I want to match the name of an Android device (e.g. "Galaxy Nexus") with a JavaScript RegEx pattern.

My user agent looks like this:

"Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"

If I take everything between the ";" and "Build/" then I get the device name. But it has to be the last occurence of ";" before "Build/".

At the moment I have the following expression:

var match = navigator.userAgent.match(/;[\s\S]*Build/)[0];

The problem is, that my expression takes everything between the FIRST semicolon and INCLUDES "Build/". So I get:

"; U; Android 4.0.2; en-us; Galaxy Nexus Build"

Does anyone knows how I can make my expression smarter to just get "Galaxy Nexus Build"?

3

There are 3 answers

0
Sirus64 On BEST ANSWER

You can test :

var txt = "Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30";
var regex = /;\s*([^;]+)\s+Build\//g;
var match = regex.exec(txt)[1];
alert("#" + match + "#");

http://jsfiddle.net/7AMrt/

0
Andrew Cheong On

Exclude the possibility of semicolons instead of using [\s\S]:

/;[^;]*Build/
0
Casimir et Hippolyte On

You can have the exact result in one shot using this:

var regex = /[^;\s][^;]+?(?=\s+build\b)/i;

or if you want to be sure there is a closing parenthesis after build:

var regex = /[^;\s][^;]+?(?=\s+build\b[^)]*\))/i;


Explanation:

[^;\s]     # a character that is not a ; or a space (avoid to trim the result after)
[^;]+?     # all characters that are not a ; one or more times with a lazy
           # quantifier (to not capture the leading spaces)

(?=        # lookahead (this is just a check and is not captured)
    \s+    # leading spaces
    build  #  
    \b     # word boundary 
)          # close the lookahead   

Since I exclude the ; from the character class, there is no need to write the literal ; before.