get Browser Name from user agent via regex - Java Network

Java examples for Network:User Agent

Description

get Browser Name from user agent via regex

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] argv) throws Exception {
        String userAgent = "java2s.com";
        System.out.println(getBrowserName(userAgent));
    }/*from   w  w w  .j  av a 2 s.  co  m*/

    public static List<String> getBrowserName(String userAgent) {
        String browserName = userAgent.toLowerCase();
        String msieRegx = ".*msie.*";
        String operaRegx = ".*opera.*";
        String firefoxRegx = ".*firefox.*";
        String chromeRegx = ".*chrome.*";
        String webkitRegx = ".*webkit.*";
        String mozillaRegx = ".*mozilla.*";
        String safariRegx = ".*safari.*";
        String version = "";
        List<String> browserList = new ArrayList<String>();
        if (Pattern.matches(msieRegx, browserName)
                && !Pattern.matches(operaRegx, browserName)) {
            browserList.add("IE");
        } else if (Pattern.matches(firefoxRegx, browserName)) {
            browserList.add("Firefox");
        } else if (Pattern.matches(chromeRegx, browserName)
                && Pattern.matches(webkitRegx, browserName)
                && Pattern.matches(mozillaRegx, browserName)) {
            browserList.add("Chrome");
        } else if (Pattern.matches(operaRegx, browserName)) {
            browserList.add("Opera");
        } else if (Pattern.matches(safariRegx, browserName)
                && !Pattern.matches(chromeRegx, browserName)
                && Pattern.matches(webkitRegx, browserName)
                && Pattern.matches(mozillaRegx, browserName)) {
            browserList.add("Safari");
        } else {
            browserList.add("unknow");
        }
        if (!browserList.get(0).equals("unknow")) {
            if (browserList.get(0).equals("IE")) {
                version = browserName
                        .substring(browserName.indexOf("msie"));
                version = version.split(";")[0].split(" ")[1];
                if (version != null && version.indexOf(".") > 0) {
                    version = version.substring(0, version.indexOf("."));
                }
            } else {
                version = browserName.substring(browserName
                        .indexOf(browserList.get(0).toLowerCase()));
                version = version.split(" ")[0].split("/")[1];
                if (version != null && version.indexOf(".") > 0) {
                    version = version.substring(0, version.indexOf("."));
                }
            }
        }
        browserList.add(version);
        return browserList;
    }
}

Related Tutorials