Code Fragment-使用正则表达式表示过滤

来源:互联网 发布:网络治疗 编辑:程序博客网 时间:2024/06/07 01:02

本文参考自《会说话的代码》,本书值得一看

一个文本框中,只允许下列字符:0~9,a,b,e,:。那么对应的检验方法可能如下:

public static boolean isValidate1(char text) {String[] allowedChars = new String[] { "0", "1", "2", "3", "4", "5","6", "7", "8", "9", "a", "b", "e", ":" };for (String ac : allowedChars) {if (ac.charAt(0) == text) {return true;}}return false;}

使用正则表达式:

public static boolean isValidate2(char text) {return String.valueOf(text).matches("[0~9abe:]");}

原创粉丝点击