Java-判断特殊字符

示例代码(可运行)

String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t";

public static void main(String[] args) {
	System.out.println(hasSpecialChar("", regEx));
	System.out.println(hasSpecialChar(" ", regEx));
	System.out.println(hasSpecialChar("faf", regEx));
	System.out.println(hasSpecialChar("fa fa", regEx));
	System.out.println(hasSpecialChar("fa(", regEx));
}

public static boolean hasSpecialChar(String str, String regEx) {
	Pattern p = Pattern.compile(regEx);
	Matcher m = p.matcher(str);

	return m.find();
}

以上代码可以运行,但是特殊字符不包含减号("-"),如果要过滤减号,则需要做特殊处理("\\-")。

String regEx1 = "[_`~!@#$%^&*()\\-+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t";

减号是特殊又特殊的,作为标记。

猜你喜欢

转载自blog.csdn.net/A_bad_horse/article/details/113996831