java实现汉字判断+中文符号判断

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qwkxq/article/details/53508736

java一般的中文判断都是利用正则表达式


Pattern pattern = Pattern.compile("[\u4e00-\u9fcc]+");
System.out.println(pattern.matcher(str).find());

或者


System.out.println(str.matches("[\u4e00-\u9fcc]+"));



这种方式会有一些生僻的汉字不能识别,而且也不能匹配中文符号如“”,;等

在Java中,主要使用 Character类处理字符有关功能,这里使用它提供的内部类来判断中文

1.Character.UnicodeBlock

判断汉字:

private static boolean isChineseByBlock(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C//jdk1.7
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D//jdk1.7
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT) {
			return true;
		}
		return false;
	}



判断中文符号:

private static boolean isChinesePuctuation(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS
                || ub == Character.UnicodeBlock.VERTICAL_FORMS) {//jdk1.7
			return true;
		}
		return false;
	}


2.Character.UnicodeScript(jdk1.7才提供)

Character.UnicodeScript提供了更为简洁的判断汉字的方式:


private static boolean isChineseByScript(char c) {
		Character.UnicodeScript sc = Character.UnicodeScript.of(c);
        if (sc == Character.UnicodeScript.HAN) {
        	return true;
        }
        return false;
	}



阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页