手机号正则表达式
package cn.itcast_01;
import java.util.Scanner;
/*
* 正则表达式:符合一定规则的字符串。
*/
public class RegexDemo2 {
public static void main(String[] args) {
// 创建键盘录入对象
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的QQ号码:");
String qq = sc.nextLine();
System.out.println("checkQQ:" + checkQQ(qq));
}
public static boolean checkQQ(String qq) {
// String regex ="[1-9][0-9]{4,14}";
// //public boolean matches(String regex)告知此字符串是否匹配给定的正则表达式
// boolean flag = qq.matches(regex);
// return flag;
//return qq.matches("[1-9][0-9]{4,14}");
return qq.matches("[1-9]\\d{4,14}");
}
}
邮箱正则表达式
package cn.itcast_02;
import java.util.Scanner;
/*
* 校验邮箱
*
* 分析:
* A:键盘录入邮箱
* B:定义邮箱的规则
* 1517806580@qq.com
* liuyi@163.com
* linqingxia@126.com
* fengqingyang@sina.com.cn
* fqy@itcast.cn
* C:调用功能,判断即可
* D:输出结果
*/
public class RegexTest {
public static void main(String[] args) {
//键盘录入邮箱
Scanner sc = new Scanner(System.in);
System.out.println("请输入邮箱:");
String email = sc.nextLine();
//定义邮箱的规则
//String regex = "[a-zA-Z_0-9]+@[a-zA-Z_0-9]{2,6}(\\.[a-zA-Z_0-9]{2,3})+";
String regex = "\\w+@\\w{2,6}(\\.\\w{2,3})+";
//调用功能,判断即可
boolean flag = email.matches(regex);
//输出结果
System.out.println("flag:"+flag);
}
}
String regex = "\\b\\w{3}\\b"; 使用 \b控制单词边界 举例:hello world?haha;xixi
package cn.itcast_05;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* 获取功能:
* 获取下面这个字符串中由三个字符组成的单词
* da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?
*/
public class RegexDemo2 {
public static void main(String[] args) {
// 定义字符串
String s = "da jia ting wo shuo,jin tian yao xia yu,bu shang wan zi xi,gao xing bu?";
// 规则
String regex = "\\b\\w{3}\\b";
// 把规则编译成模式对象
Pattern p = Pattern.compile(regex);
// 通过模式对象得到匹配器对象
Matcher m = p.matcher(s);
// 调用匹配器对象的功能
// 通过find方法就是查找有没有满足条件的子串
// public boolean find()
// boolean flag = m.find();
// System.out.println(flag);
// // 如何得到值呢?
// // public String group()
// String ss = m.group();
// System.out.println(ss);
//
// // 再来一次
// flag = m.find();
// System.out.println(flag);
// ss = m.group();
// System.out.println(ss);
while (m.find()) {
System.out.println(m.group());
}
// 注意:一定要先find(),然后才能group()
// IllegalStateException: No match found
// String ss = m.group();
// System.out.println(ss);
}
}
jia
jin
yao
xia
wan
gao
A:字符
x 字符 x。举例:'a'表示字符a
\\ 反斜线字符。
\n 新行(换行)符 ('\u000A')
\r 回车符 ('\u000D')
B:字符类
[abc] a、b 或 c(简单类)
[^abc] 任何字符,除了 a、b 或 c(否定)
[a-zA-Z] a到 z 或 A到 Z,两头的字母包括在内(范围)
[0-9] 0到9的字符都包括
C:预定义字符类
. 任何字符。我的就是.字符本身,怎么表示呢? \.
\d 数字:[0-9]
\w 单词字符:[a-zA-Z_0-9]
在正则表达式里面组成单词的东西必须有这些东西组成
D:边界匹配器
^ 行的开头
$ 行的结尾
\b 单词边界
就是不是单词字符的地方。
举例:hello world?haha;xixi
E:Greedy 数量词
X? X,一次或一次也没有
X* X,零次或多次
X+ X,一次或多次
X{n} X,恰好 n 次
X{n,} X,至少 n 次
X{n,m} X,至少 n 次,但是不超过 m 次