import java.util.Arrays;
public class Demo131 {
public static void main(String[] args) {
matchPhone("1356082481");
matchTel("020-3322560");
splitTest2();
repalcePhone();
repalce2();
}
/*匹配一个手机号
手机号码的规则:
1. 首位必须是1.
2. 第二位: 3 4 、5 、 7、 8、
3. 长度 必须是11位
*/
public static void matchPhone(String phone){
String reg = "1[34578]\\d{9}";
System.out.println(phone.matches(reg)?"合法手机号":"非法手机号");
}
/*
* 匹配一个固定电话
* 规则:
* 区号:
* 1. 长度3~4位.
* 2. 必须以0开头。
* 主机号:
* 1.首位不能是0.
* 2.长度 是: 7~8位
*/
public static void matchTel(String tel){
String reg = "0\\d{2,3}-\\d{6,7}";
System.out.println(tel.matches(reg)?"合法固话号":"非法固话号");
}
//需求: 根据空格切割。
public static void splitTest1(){
String str = "明 天 学 i o";
String reg = " +";
String[] datas = str.split(reg);
System.out.println("数组的元素:"+ Arrays.toString(datas));
}
//需求: 根据重叠词进行切割。
public static void splitTest2(){
String str = "我要要要成为为高富富富富富富帅"; // 我 成 高 帅
String reg = "(.)\\1+";
/*
后面的一个正则字符要使用到前面正则匹配的内容。 前面正则的内容需要被复用起来。 如果正则的内容需要被复用,那么就需要进行分组。
每一个组都有一个编号,编号从1开始。
*/
String[] datas = str.split(reg);
System.out.println("数组的元素:"+ Arrays.toString(datas));
}
//需求: 把手机号替换成***。 一3五
public static void repalcePhone(){
String str = "如果有需要请联系:13556084321如果有需要请联系:13556084321如果有需要请联系:13556084321如果有需要请联系:13556084321"
+ "如果有需要请联系:13556084321如果有需要请联系:13556084321如果有需要请联系:13556084321如果有需要请联系:13556084321如果有需要请联系:13556084321";
String reg = "1[34578]\\d{9}";
str = str.replaceAll(reg, "****");
System.out.println("帖子的内容:"+ str);
}
//需求: 把重叠词替换成单个字符。
public static void repalce2(){
String str = "我我我我我要要要成成成成成成为为高富富富富富富帅帅帅帅帅帅帅帅帅帅帅帅帅帅帅帅帅帅帅帅";
str = str.replaceAll("(.)\\1+", "$1"); //注意引用正则的内容如果不是在一个正则表达式内部,那么需要使用 : "$组号" 进行引用
System.out.println(str);
}
}
JAVA小练习131——正则的练习--正则对字符串的常见的操作
猜你喜欢
转载自blog.csdn.net/Eric_The_Red/article/details/91971932
今日推荐
周排行