Java、Android 常用正則判斷

	/**
     * 判斷字符串中是否包含中文
     * @param str
     * 待校驗字符串
     * @return 是否爲中文
     * @warn 不能校驗是否爲中文標點符號
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 判斷是否含有特殊字符
     *
     * @param str
     * @return true爲包含,false爲不包含
     */ public static boolean isSpecialChar(String str) {
         String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t";
         Pattern p = Pattern.compile(regEx);
         Matcher m = p.matcher(str); return m.find();
     }

    /**
     * 判斷字符串是否爲數字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /** 判斷一個字符串是否含有數字
     *
     * @param content
     * @return
     */
    public static boolean HasNumeric(String str) {
        boolean flag = false;
        Pattern p = Pattern.compile(".*\\d+.*");
        Matcher m = p.matcher(str);
        if (m.matches()) {
            flag = true;
        }
        return flag;
    }

    /**
     * 是否僅含有數字和字母
     * @param str
     * @return
     */
    public static boolean isLetterDigit(String str) {
        String regex = "^[a-z0-9A-Z]+$";
        return str.matches(regex);
    }

    /**
     * 判斷是否爲數字和字母
     * @param str
     * @return
     */
    public static boolean isNumAndLetter(String str){
        Pattern pattern = Pattern.compile("[0-9A-Za-z]+");
        return pattern.matcher(str).matches();
    }
    
	 /**
     * 判斷是否有表情符號
     * @param string
     * @return
     */
    public static boolean isEmoji(String str) {
        @SuppressLint("WrongConstant")
        Pattern p = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(str);
        return m.find();
    }
	
	 /**
     * 判斷是否是IP地址
     * @param string
     * @return
     */
	public static boolean isIP(CharSequence str) {
        return isMatch("((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)", str);
    }

 	/**
     * 判斷是否是URL
     * @param string
     * @return
     */
	public static boolean isURL(CharSequence str) {
        return isMatch("[a-zA-z]+://[^\\s]*", str);
    }

	/**
     * 判斷是否是Email
     * @param string
     * @return
     */
	public static boolean isEmail(CharSequence str) {
        return isMatch("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$", str);
    }

	public static boolean isMatch(String var0, CharSequence str) {
        return str!= null && str.length() > 0 && Pattern.matches(var0, str);
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章