Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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"?

share|improve this question
    
does it have to be only with matching a regex? you could split(";") the result and the last one will be what you want – user1651640 Jul 15 '13 at 18:17

3 Answers 3

up vote 1 down vote accepted

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/

share|improve this answer

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.

share|improve this answer

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

/;[^;]*Build/
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.