Question

I have a string:

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)

I want to know what version of Firefox is in the string (3.5.2).

My current regex is:

Firefox\/[0-9]\.[0-9]\.[0-9]

and it returns Firefox/3.5.2

I only want it to return 3.5.2 from the Firefox version, not the other versions in the string. I already know the browser is Firefox.

Was it helpful?

Solution

(?<=Firefox/)\d+(?:\.\d+)+

will return 3.5.2 as the entire match (using lookbehind - which is not available in all regex flavors, though, especially JavaScript).

So, if it has to be JavaScript, search for Firefox/(\d+(?:\.\d+)+) and use match no. 1.

Since in theory there could be more than one digit (say, version 3.10.0), I've also changed that part of the regex, allowing for one or more digits for each number. Also, there is no need to escape the slash.

OTHER TIPS

Firefox\/([0-9]\.[0-9]\.[0-9])

Create a capture group around the numbers like I have done above with the (). Then the regex you want will be in the 2nd index in the array that is returned. e.g for zero based languages matchedArray[1] and or 1 based languages its matchedArray[2]

Firefox\/([0-9]\.[0-9]\.[0-9])

and extract match #1, however this is done in your (unspecified, though one suspects JavaScript) regex engine. Or, if this is very annoying to do, and your regex supports lookbehind:

(?<=Firefox\/)[0-9]\.[0-9]\.[0-9]

Firefox\/([0-9]\.[0-9]\.[0-9])

Depending on your language (i'm assuming js) it'll be the second element in the array

i.e.


var regex = /Firefox\/([0-9]\.[0-9]\.[0-9])/
var matches = useragent.match(regex);
alert(matches[1]); // 3.5.2

Sometimes the user-agent also contains characters, e.g.:

Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b9pre) Gecko/20101228 Firefox/4.0b9pre

Internet Explorer is the only other browser where I've seen the characters as part of the version information:

Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0 ; .NET CLR 2.0.50215; SL Commerce Client v1.0; Tablet PC 2.0

Also, there can be Firefox user-agent strings with only two version digits like this one:

Mozilla/5.0 (X11; U; Linux armv7l; en-US; rv:1.9.2a1pre) Gecko/20091127 Firefox/3.5 Maemo Browser 1.5.6 RX-51 N900

Based on that I came up with this regex pattern:

Firefox\/([\d]+\.[\w]?\.?[\w]+) 

It will match any version number with 2-3 levels and numbers > 10 but also allow characters in the 2nd or 3rd level.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top