集册 Java实例教程 通过regex从用户代理获取浏览器名称

通过regex从用户代理获取浏览器名称

欢马劈雪     最近更新时间:2020-01-02 10:19:05

543
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
通过正则表达式从用户代理获取浏览器名称
// 来 自 nowjava - 时  代  Java

//package com.nowjava;

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 = "nowjava.com";

        System.out.println(getBrowserName(userAgent));

    }


    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.*";/** 时 代 J a v a 公 众 号 提 供 **/

        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("."));

           
展开阅读全文