判断String中是否是数字、是否是汉字以及截取汉字与数字

在实际应用的开发过程中,经常需要取出String中数字,用来满足实际的应用场景,下面的代码实现了String中是否包含数字、是否是数字、截取String中的数字、以及判断是否是汉字、截取String中的文字与数字的功能.

/**
     * 是否是数字
     */
    public static boolean isNumber(String s) {
        Pattern p = Pattern.compile("[0-9]*");
        Matcher m = p.matcher(s);
        if (m.matches()) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 是否包含数字
     */
    public static boolean isContainsNumber(String time) {
        boolean isNum = false;
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(time);
        String trim = m.replaceAll("").trim();


        if (trim.length() > 0) {
            isNum = true;
        } else {
            isNum = false;
        }


        return isNum;
    }

    /**
     * 截取string中的数字
     */
    private static String getStringNum(String time) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(time);
        String trim = m.replaceAll("").trim();
        if (trim.length() == 1) {
            trim = "0" + trim;
        }
        return trim;
    }

  /**
   * 根据中文unicode范围判断u4e00 ~ u9fa5,是否是汉字
   */
    private static boolean isChinese(String str) {
        String regEx1 = "[\\u4e00-\\u9fa5]+";
        String regEx2 = "[\\uFF00-\\uFFEF]+";
        String regEx3 = "[\\u2E80-\\u2EFF]+";
        String regEx4 = "[\\u3000-\\u303F]+";
        String regEx5 = "[\\u31C0-\\u31EF]+";
        Pattern p1 = Pattern.compile(regEx1);
        Pattern p2 = Pattern.compile(regEx2);
        Pattern p3 = Pattern.compile(regEx3);
        Pattern p4 = Pattern.compile(regEx4);
        Pattern p5 = Pattern.compile(regEx5);
        Matcher m1 = p1.matcher(str);
        Matcher m2 = p2.matcher(str);
        Matcher m3 = p3.matcher(str);
        Matcher m4 = p4.matcher(str);
        Matcher m5 = p5.matcher(str);
        if (m1.find() || m2.find() || m3.find() || m4.find() || m5.find())
            return true;
        else
            return false;
    }

    /**
     * 截取 string 中 文字与数字
     */


    public static String divideRoomName(String roomName) {
        String[] name_Id = new String[2];
        String n = "";
        String m = "";
        if (roomName.length() > 0) {
            for (int i = 0; i < roomName.length(); i++) {
                if (roomName.substring(i, i + 1)
                        .matches("[\u4e00-\u9fa5]+")) {
                    n += roomName.substring(i, i + 1);
                } else {
                    m += roomName.substring(i, i + 1);
                }
            }
          name_Id[0] = n;
          name_Id[1] = m;
        }
        return n;
    }

猜你喜欢

转载自blog.csdn.net/erweidetaiyangxi/article/details/79020174