Checking browser and version with REGEX

Asked

Viewed 355 times

1

I am working on a Vb.net MVC system and need to detect the browser and version.

I will only use Chrome, and IE9+. I was wondering if I could simplify the verification structure using Regex.

Below the section I use to make the check.

If (Not Request.Browser.ToString().ToLower().Contains("ie") And
        Not Request.Browser.ToString().ToLower().Contains("internet explorer") And
        Not Request.Browser.ToString().ToLower().Contains("chrome")) Then

        Return View("IncompativelAgent")
    Else
        If Not Request.Browser.ToString().ToLower().Contains("chrome") And Request.Browser.MajorVersion < 9 Then
            Return View("IncompativelAgent")
        End If
    End If

I find it very inelegant the way it is.

  • You can create methods for this and return TRUE or FALSE.

  • the issue is not the encapsulation but how to do the regex check to avoid these Ifs.

  • 1

    Related : http://answall.com/questions/46871/identificar-browser-e-sua-vers%C3%A3o only changes language.

  • William, does not answer, the codifo came to be bigger than mine, I think that if it is not for regex, I can hardly reduce it.

  • My algorithm works and is running well, I wanted to simplify this stretch of Ifs

1 answer

3


Following this link to obtain the information :

C#

System.Web.HttpBrowserCapabilities browser = Request.Browser;

string pattern = @"ie|internet explorer|chrome";

MatchCollection matches = Regex.Matches(browser.Browser, pattern, RegexOptions.IgnoreCase)

if(matchs.Count == 0 And browser.Version < 9){
    Return View("IncompativelAgent");
}

VB

    Dim regex As Regex = New Regex("ie|internet explorer|chrome", RegexOptions.IgnoreCase)
    Dim match As Match = regex.Match(Request.Browser.Browser)
    If (Not match.Success Or (match.Success And Request.Browser.MajorVersion < 9)) Then
        Return View("IncompativelAgent")
    End If

Obs

I’m not knowledgeable, build on research.

Links

How to: Detect Browser Types and Browser Capabilities in ASP.NET Web Forms
Check Browser version and name (VB.net)
VB.NET Regex.Match Function Examples

  • It has how to translate to VB?

  • 1

    @Paulohdsousa I’m going to owe you, as I said I do not know well C# and VB, but link above has the information in VB.

  • I tried to translate with a website here, also could not... But it’s worth the help.

  • 1

    @Paulohdsousa I rode a VB, see if this ok, please

  • Guilgerme, perfect!!! I made a small change to contemplate the rule however it was just what I wanted, I exchanged 10 lines for 5. Thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.