正则表达式检测 IE 5、6、7 和 8,但没有其他

Regex to detect IE 5, 6, 7 and 8 but no others

我整理了这个正则表达式,它应该只 return 用户代理字符串为 IE 5、6、7 和 8 的匹配项。显然,这里的主要目标之一是避免混淆 IE11用户代理字符串..

这个正则表达式有效吗(我错过了什么)?

.*MSIE [5-8]\b((?!Trident/4.0)).*

更新

下面匹配 5、6、7 和 8 的所有用户代理字符串。和 9、10 的 none。但是它确实匹配 IE11 的一个,return 从 .Net 使用Request.UserAgent

'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729)'

^.*MSIE [5-8](?:\.[0-9]+)?(?!.*Trident\/6\.0\)).*$

这里是list of user agent strings across IE versions。要验证 IE 5、6、7 和 8 用户代理字符串,您只需检查末尾的 "Trident/6.0)"。

使用这个正则表达式:^.*MSIE [5-8](?:\.[0-9]+)?(?!.*Trident\/[5-9]\.0).*$

regex101 example

编辑:

根据MSDN User Agent documentation

When the F12 developer tools are used to change the browser mode of Internet Explorer, the version token of the user-agent string is modified to appear so that the browser appears to be an earlier version.

This is done to allow browser specific content to be served to Internet Explorer and is usually necessary only when websites have not been updated to reflect current versions of the browser.

When this happens, a Trident token is added to the user-agent string.

This token includes a version number that enables you to identify the version of the browser, regardless of the current browser mode.

Token         Description
Trident/7.0   IE11
Trident/6.0   Internet Explorer 10
Trident/5.0   Internet Explorer 9
Trident/4.0   Internet Explorer 8

所以,正则表达式应该检查 MSIE 版本后面是否没有 'Trident/5.0',直到 'Trident/7.0': ^.*MSIE [5-8](?:\.[0-9]+)?(?!.*Trident\/[5-9]\.0).*$。当 'Trident/10'+ 发布时,将有必要对其进行更新。或者,这里是: ^.*MSIE [5-8](?:\.[0-9]+)?(?!.*Trident\/(?:[5-9]|1[0-9])\.0).*$.