正则表达式介绍

String提供的正则表达式的方法的书写规则

正则表达式总结

正则表达式作用:

作用三:搜索替换

案例分析及代码(图片解析)

代码:
代码一:校验手机号和邮箱格式是否正确
package com.itheima.day15_regex;
import java.util.Scanner;
public class RegexTest3 {
public static void main(String[] args) {
checkEmail();
}
public static void checkPhone() {
while (true) {
System.out.println("请您输入您的电话号码(手机|座机):");
Scanner sc = new Scanner(System.in);
String phone = sc.nextLine();
if (phone.matches("(1[3-9]\\d{9}|(0\\d{2,7}-?[1-9]\\d{4,19}))")){
System.out.println("您输入的号码格式正确~~~");
break;
}else {
System.out.println("您输入的号码格式不正确~~~");
}
}
}
public static void checkEmail() {
while (true) {
System.out.println("请您输入您的邮箱:");
Scanner sc = new Scanner(System.in);
String email = sc.nextLine();
if (email.matches("\\w{2,}@(\\w{2,20}\\.\\w{2,10}){1,2}")){
System.out.println("您输入的邮箱格式正确~~~");
break;
}else {
System.out.println("您输入的邮箱格式不正确~~~");
}
}
}
}

代码二:使用正则表达式做搜索替换,内容分割。
package com.itheima.day15_regex;
import java.util.Arrays;
public class RegexTest4 {
public static void main(String[] args) {
String str1 ="古力娜扎ai8888迪丽热巴999aa5566马尔扎哈fbbfsfs42425卡尔扎巴";
System.out.println(str1.replaceAll("\\w+", "-"));
String str2 ="我我我喜欢编编编编编编编编编编编编程程程!";
System.out.println(str2.replaceAll("(.)\\1+","$1"));
String str3 = "古力娜扎ai8888迪丽热巴999aa5566马尔扎哈fbbfsfs42425卡尔扎巴";
String[] names =str3.split("\\w+");
System.out.println(Arrays.toString(names));
}
}
