作用一:用来校验数据格式是否合法
作用二:在一段文本中查找满足要求的内容
例如:用于判断一个QQ号是否格式合法
正常写法
public class Test {
public static void main(String[] args) {
System.out.println(checkQQ("12345678"));
}
public static boolean checkQQ(String qq){
// qq号不能为null,不能以0开头,满足长度为6~20
if (qq == null || qq.startsWith("0") || qq.length() <6 || qq.length() >20){
return false;
}
// 判断qq号中是否都是数字
for (int i = 0; i < qq.length(); i++) {
char ch = qq.charAt(i);
if (ch < '0' || ch > '9'){
return false;
}
}
// 说明qq号肯定是合法的
return true;
}
}
用正则表达式
public class Test {
public static void main(String[] args) {
System.out.println(checkQQ("12345678"));
}
public static boolean checkQQ(String qq){
// qq号不能为null,不能以0开头,满足长度为6~20
return qq != null && qq.matches("[1-9]\\d{5,19}");
}
}
public boolean matches(String regex) 判断字符串是否匹配正则表达式,匹配返回true,不匹配返回false。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//checkPhome();
checkEmail();
}
public static void checkPhome(){
while (true) {
System.out.println("请您输入您的电话号码(手机|座机):");
Scanner sc = new Scanner(System.in);
String phone = sc.next();
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 phone = sc.next();
if (phone.matches("\\w{2,}@\\w{2,10}(\\.\\w{2,10}){1,2}")){
System.out.println("您输入的邮箱格式正确!");
break;
}else {
System.out.println("您输入的邮箱格式有误!");
}
}
}
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
method1();
}
public static void method1(){
String date = "电话:13456789987,19876543211\n" +
"邮箱:[email protected]\n" +
"座机电话:01036515895,010-98951256\n" +
"邮箱2:[email protected]\n" +
"热线电话:400-615-9558,400-618-4000,4006159558,4006184000\n";
// 定义爬取规则(正则表达式)
String regex = "(400-?\\d{3,7}-?\\d{3,7})|(1[3-9]\\d{9})|(0\\d{2,7}-?[1,9]\\d{4,19})|(\\w{2,}@\\w{2,10}(\\.\\w{2,10}){1,2})";
// 把正则表达式封装成一个Pattern对象
Pattern pattern = Pattern.compile(regex);
// 通过pattern对象得到查找内容的匹配器
Matcher matcher = pattern.matcher(date);
// 通过匹配器开始去内容中查找信息
while (matcher.find()){
String rs = matcher.group(); //取出信息
System.out.println(rs);
}
}
}
方法名 | 说明 |
---|---|
public String replaceAll(String regx,String newStr) | 按照正则表达式匹配的内容进行替换 |
public String [ ] split(String regex) | 按照正则表达式匹配的内容进行分割字符串,返回一个字符串数组 |
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
// 需求:把中间的非中文字符替换成 ”-“
String s1 = "张三asd16李四5464王五aq1564a赵六";
System.out.println(s1.replaceAll("\\w+", "-"));
// 需求:将”我我我我喜欢编编编编编编编程“优化为”我喜欢编程“
String s2 = "我我我我喜欢编编编编编编编程";
/*
* (.)一组:匹配任意字符的
* \\1:为这个组声明一个组号:1号
* +:数量为1个或多个,声明必须是重复的字
* $1:可以取到第一组代表的那个重复的字
* */
System.out.println(s2.replaceAll("(.)\\1+", "$1"));
// 需求:把字符串中的人名获取出来
String s3 = "张三asd16李四5464王五aq1564a赵六";
String[] names = s3.split("\\w+");
System.out.println(Arrays.toString(names));
}
}