简体   繁体   中英

RegEx: Match Android device name with JavaScript

I want to match the name of an Android device (eg "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"?

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/

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.

排除使用分号而不是使用[\\s\\S]的可能性:

/;[^;]*Build/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM