Question

I need your help creating an IE specific regular expression for the user agent string. My goal is to get the correct IE version (including IE11), and also checking whether if the browser is running "Compat View".

So, for example, my desired result for IE9 in normal mode: IE 9.0 And IE9 in "Compat View": IE 9.0 CV

This pattern works for up to IE 10, when not taking compat view in to consideration: MSIE ([0-9]{1,}[\.0-9]{0,})

However, IE9 in compat view will have a user agent string similar to ... MSIE 7.0 ... Trident/5.0. Also, IE11 will ni longer use MSIE at all in the string (see example below).

I don't know regex very well, so I need your help with the pattern. Though I think the trident pattern should be pretty obvious, /Trident\/\d/.

I will be using this in C#, so I suppose I need to do something like this (suggestions welcome):

var regex = new Regex(@"MSIE ([0-9]{1,}[\.0-9]{0,})");
var match = regex.Match(Request.UserAgent);
if (match.Success)
    //handle match.Groups

Some info that might be useful:

IE9's user agent string:

Similar to IE8, IE9’s Compatibility View will map to IE7 Standards Mode, and IE9’s UA string when in Compatibility View will be:

Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0) In Compatibility View, IE9 reports itself as IE7 through the application version number (Mozilla/4.0) and version token (MSIE 7.0). This is done for compatibility. An incremented Trident token, from ‘Trident/4.0’ to ‘Trident/5.0’, allows websites to distinguish between IE9 running in Compat View and IE8 running in Compat View.

IE11's user agent string:

Windows 7 IE11 example: Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko

Similar useful thread

Was it helpful?

Solution

Using regex pattern

(?:\b(MS)?IE\s+|\bTrident\/7\.0;.*\s+rv:)(\d+)

you match all current known IE browser user agent strings and the number matching in group #1 determinate version of IE (if not running in Compatibility View).


To find out if IE is running in Compatibility View, lookup for match of

\bMSIE\s+7\.0;.*\bTrident\/(\d+)\.0

The number matching in group #1 (after keyword "Trident") determinate version of IE in Compatibility View as follow:

4 -> IE  8 in CV
5 -> IE  9 in CV
6 -> IE 10 in CV
7 -> IE 11 in CV
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top