java工具类(字符串字符长度计算和特殊字符正则)

/**
 * 
 * @author zs
 *	字符串  长度校验与正则匹配
 */
public class StringCheckUtil {
	
	/**
	 * 获取字符长度(中文2个字符)
	 * @param str
	 * @return
	 */
	public static int getTrueLength(String str) {
		int valueLength = 0;
		String chinese = "[\u4e00-\u9fa5]";
		for (int i = 0; i < str.length(); i++) {
			String temp = str.substring(i, i + 1);
			if (temp.matches(chinese)) {
				valueLength += 2;
			} else {
				valueLength += 1;
			}
		}
		return valueLength;
	}
	
	/**
	 * 校验是否包含特殊字符
	 * @param str
	 * @return
	 */
	public static boolean isContainSpecialChar(String str) {
		String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
		Pattern p = Pattern.compile(regEx);
		Matcher matcher = p.matcher(str);
		boolean b = matcher.find();
		return b;
	}

}

猜你喜欢

转载自blog.csdn.net/qq_31024823/article/details/80165515