Reputation: 489
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.
Upvotes: 0
Views: 8347
Reputation: 336198
/(?<=Firefox\/)\d+(?:\.\d+)+/
will return 3.5.2 as the entire match (using lookbehind - which is supported in most browsers nowadays).
If your JavaScript engine still does not support this (looking at Safari in February 2022), 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.
Upvotes: 3
Reputation: 460
Firefox\/(\d+(?:\.\d+)+)
Depending on your language (I’m assuming JS) it’ll be the second element in the array, i.e.
const regex = /Firefox\/(\d+(?:\.\d+)+)/;
const matches = useragent.match(regex);
console.log(matches[1]); // "3.5.2"
Upvotes: 1
Reputation: 124297
Firefox\/(\d+(?:\.\d+)+)
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 engine supports lookbehind:
(?<=Firefox\/)\d+(?:\.\d+)+
Upvotes: 1
Reputation: 22418
Firefox\/(\d+(?:\.\d+)+)
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 languages with zero-based lists, matchedArray[1]
, and for ones with 1-based lists, matchedArray[2]
.
Upvotes: 2
Reputation: 211
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.
Upvotes: 1