views:

62

answers:

2

I've taken a regular expression from jQuery to detect if a browser's engine is WebKit and gets it's version number, it returns 3 values extracted from the userAgent string: webkit/….…, webkit and ….… [“….…” being the version number].

I would like the regular expression to return just 2 values: webkit and ….….

I'm rubbish at regular expressions, so please can you give an explanation of the expression with your answer.

The regular expression I'm currently working with and wish to improve is: /(webkit)[\/]([\w.]+)/.

From Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_6; en-us) AppleWebKit/525.13 (KHTML, like Gecko) Version/3.1 Safari/525.13 this regular expression would return: webkit/525.13,webkit,525.13. I would wish it only returned webkit,525.13.

I appreciate all your help, thanks in advance!

+1  A: 

In regular expressions, the values you get returned are those in parentheses:

/([a-z]+)-#(\d+)/.exec("abc-#123")

// ["abc-#123", "abc", "123"]

You can just make the groups non-matching by adding ?: at the start of it:

/(?:[a-z]+)-#(\d+)/.exec("abc-#123")

// ["abc-#123", "123"]

Edit after re-reading your question.

The return from the regex will contain (as shown in my examples above) the entire matched string, then the matched groups. If you want just the matched groups, just slice off the first value:

myRegex.exec(userAgent).slice(1);

// ["webkit", "525.13"]   <-- note that this is an array
nickf
Thanks! I'd imagine though not bothering to `slice` and never referencing the first value would be more efficient, as the first value is created anyway and then sliced.Can I not create an expression that does not return the entire matched string, and just the groups, as in my question. I understand this may not be possible.Thank you again for all your help!
Jonathon David Oates
@Jay: no it's not possible.
nickf
A: 

Hem, if you are using jQuery there is a build-in method for this propose that gives you and already chewed result. http://api.jquery.com/jQuery.browser/

Cesar
No, I'n not using jQuery, sorry, I could have been clearer, I'm using a the regular expression jQuery uses from looking at the source. I don't want to load all of jQuery to detect WebKit, but the regular expression jQuery.browser uses should be as reliable as any.
Jonathon David Oates