0

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

4

3 回答 3

1

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/

于 2013-07-15T17:27:04.340 回答
1

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.

于 2013-07-15T18:58:35.757 回答
0

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

/;[^;]*Build/
于 2013-07-15T17:25:28.877 回答