预定义的字符 Java字符串表示
(a) \d : 0-9 (\\d)
(b) \s : 空白字符(回车,转行,空格,退格,跳格..) (\\s) (c) \w : 英文单词 + 数字 (\\w) (e) \D : 非数字 (\\D) (f) \S : 非空白字符 (\\S) (g) \W : 非单词 (\\W)
正则表达式常规的语法 [1] 量词 ---> 表示数量 (a) * : 0 ---> n : 字符 (b) + : 1 ---> n : 字符 (c) ? : 0 / 1 : 字符 (d) {n} : n 个字符 (不能多,不能少) (e) {n,}: n+ 个字符 (f) {m,n}: 最少 m 个字符, 最多 n 个字符
转义字符: \0xxxx ---> 八进制 \0xfa ---> 十六进制 \u4566 --->匹配所有的中文汉字( 简体 ): \u4E00 ---> \u9FA5 \t 制表符 \r:回车 \n: 转行 \b: 退格
表示: "[" ---> \\[ 表示: "]" ---> \\] 以什么来 "开头" ^: 锁定某个字符一定要出现在开始位置 以什么 "结尾" $:
逻辑运算符
(1) && 要在[]中引用 (2) ^ 在[]中表示非
(3) || []中可不表示
附:
验证:
public static void main(String[] args) {
// 要验证的字符串
String str = "service@xsoftlab.net";
// 邮箱验证规则
String regEx = "[a-zA-Z_]{1,}[0-9]{0,}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}";
// 编译正则表达式
Pattern pattern = Pattern.compile(regEx);
// 忽略大小写的写法
// Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
// 字符串是否与正则表达式相匹配
boolean rs = matcher.matches();
System.out.println(rs);
}
查找字符:
public static void main(String[] args) {
// 要验证的字符串
String str = "baike.xsoftlab.net";
// 正则表达式规则
String regEx = "baike.*";
// 编译正则表达式
Pattern pattern = Pattern.compile(regEx);
// 忽略大小写的写法
// Pattern pat = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
// 查找字符串中是否有匹配正则表达式的字符/字符串
boolean rs = matcher.find();
System.out.println(rs);
}