一、笔记:
正则表达式:用来验证用户输入的格式,本质是一段特殊字符串
写正则表达式:以^开头 ,以$结尾,可以省略
[abc] a、b 或 c
[^abc] 任何字符,除了 a、b 或 c(否定)
[a-zA-Z] a 到 z 或 A 到 Z,两头的字母包括在内(范围)
[a-d[m-p]] a 到 d 或 m 到 p:[a-dm-p](并集)
[a-z&&[def]] d、e 或 f(交集)
[a-z&&[^bc]] a 到 z,除了 b 和 c:
[a-z&&[^m-p]] a 到 z,而非 m 到 p:
[0-9]:数字0-9
\d 数字:[0-9]
\D 非数字: [^0-9]
\s 空白字符:[ \t\n\x0B\f\r]
\S 非空白字符:[^\s]
\w 单词字符:[a-zA-Z_0-9]
\W 非单词字符:[^\w]
X? X,一次或一次也没有 0~1次
X* X,零次或多次 0~n次
X+ X,一次或多次 1~n次
X{n} X,恰好 n 次 只能是n次
X{n,} X,至少 n 次 >=n
X{n,m} X,至少 n 次,但是不超过 m 次 >=n<=m
二、实践
package com.qfedu.zhuguangyi.string_正则表达式;
import java.util.Scanner;
public class TestZhengZe {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// System.out.println("请输入字符串只能包含abc");
// String s = sc.nextLine();
// //matches(String regex) 匹配正则表达式,参数放入正则表达式
// System.out.println(s.matches("[^abc]{5}"));
// System.out.println("请输入字符串只能包含0-9的数字");
// String s = sc.nextLine();
// //matches(String regex) 匹配正则表达式,参数放入正则表达式
// System.out.println(s.matches("[0-9]{4}"));
//QQ号的规则:5~11
// System.out.println("请输入QQ号:(5~11位)");
// String qq = sc.next();
// if(qq.matches("[1-9]{1}[\\d]{4,10}")) {
// System.out.println("登录成功");
// }else {
// System.out.println("登录失败");
// }
//手机号的规则:11位 1[345789]{1}[\\d]{9}
// System.out.println("请输入手机号:");
// String shouJi = sc.next();
// System.out.println(shouJi.matches("1[345789]{1}[\\d]{9}"));
System.out.println("请输入邮箱:");
String email = sc.nextLine();
System.out.println(email.matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+"));
}
}
放弃自己,相信别人,这就是失败的原因!!!