1.字符串的合法检验
现在有一个字符串验证码 我们需要检验其的合法性 什么条件才能够使得字符串合法呢?就是6-10个字符串长度 并且以字母开头 并且其中由字母、数字、下划线构成
那么我们可以先通过自定义的方式进行检验
public class Main {public static void main(String[] args) {System.out.println(validate("aaaaaa"));}private static boolean validate(String email){// 如果参数为空的话 那么说明不合法 提醒一下并且返回falseif(email == null){System.out.println("邮箱不能为空");return false;}// 由于之后获取参数字符串中的字符方法charAt()开头需要对字符串进行长度判断 如果多次调用的话 时间方面的效率肯定很低 但是好在他是在原先字符串的基础上进行获取的 所以我们利用空间换时间的方法 拷贝一个字符串的内存 优化了时间 但多开辟了空间char[] chs = email.toCharArray();int len = chs.length;// 如果参数的长度不合要求的话 那么提醒一下并且返回false 由于长度需要多次获取 所以提前定义一个变量 用于保存这个参数的长度if(len < 6 || len > 10){System.out.println("长度不合法");return false;}// 是否以字母开头if(!isLetter(chs[0])){System.out.println("不是以字母开头");return false;}// 是否由字母、数字、下划线构成for(int i = 1; i < len; ++i){// 获取当前遍历的字符char ch = chs[i];if(isLetter(ch) || isDigit(ch) || ch == '_')continue;return false;}// 如果上述判断都没有返回false的话 那么说明这个邮箱字符串是合法的return true;}private static boolean isLetter(char ch){if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))return true;return false;}private static boolean isDigit(char ch){if(ch >= '0' && ch <= '9')return true;return false;}
}
但是我们可以看到其实我们自己自定义的方法写的很繁杂 所以我们可以引入正则表达式来替代复杂的验证逻辑
public class Main {public static void main(String[] args) {String regex = "[a-zA-Z][a-zA-Z0-9_]{5,9}";System.out.println("aaaaaa".matches(regex));}
}
public class Main {public static void main(String[] args) {String regex = "[a-zA-Z]\\w{5,9}";System.out.println("aaaaa".matches(regex));}
}