package com.common.util; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 檢測是否為移動端設備訪問 * */ public class CheckMobile { // \b 是單詞邊界(連着的兩個(字母字符 與 非字母字符) 之間的邏輯上的間隔), // 字符串在編譯時會被轉碼一次,所以是 "\\b" // \B 是單詞內部邏輯間隔(連着的兩個字母字符之間的邏輯上的間隔) static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i" +"|windows (phone|ce)|blackberry" +"|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp" +"|laystation portable)|nokia|fennec|htc[-_]" +"|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b"; static String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser" +"|[1-4][0-9]{2}x[1-4][0-9]{2})\\b"; //移動設備正則匹配:手機端、平板 static Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE); static Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE); /** * 檢測是否是移動設備訪問 * @Title: check * @param userAgent 瀏覽器標識 獲取方式:request.getHeader( "USER-AGENT" ).toLowerCase() * @return true:移動設備接入,false:pc端接入 */ public static boolean check(String userAgent){ if(null == userAgent){ userAgent = ""; } // 匹配 Matcher matcherPhone = phonePat.matcher(userAgent); Matcher matcherTable = tablePat.matcher(userAgent); if(matcherPhone.find() || matcherTable.find()){ return true; } else { return false; } } }