- package cn.itheima_01;
- import java.util.Scanner;
- /**
- *
- * 正则表达式:符合某种规则的字符串。
- *
- * 规则?
- *
- * 举例:校验qq号码. 1:要求必须是5-15位数字 2:0不能开头
- *
- *
- * @author perry
- *
- */
- public class RegaxDemo {
- public static void main(String[] args) {
- // 封装键盘录入
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入一行QQ号:");
- String s = sc.nextLine();
- boolean flag = checkQq(s);
- System.out.println(flag);
- boolean flag2 = checkQq2(s);
- System.out.println(flag2);
- }
- private static boolean checkQq2(String s) {
- String regex = "[1-9][0-9]{4,14}";
- boolean flag = s.matches(regex);
- return flag;
- }
- private static boolean checkQq(String s) {
- boolean flag = true;
- if (s.length() >= 5 && s.length() <= 15) {
- if (!s.startsWith("0")) {
- char[] ch = s.toCharArray();
- for (char chs : ch) {
- if (!(chs >= '0' && chs <= '9')) {
- flag = false;
- break;
- }
- }
- } else {
- flag = false;
- }
- } else {
- flag = false;
- }
- return flag;
- }
- }
复制代码
|
|