【大数据开发】Java语言基础——正则表达式匹配、切割、替换、获取四种常见应用day13

本文详细介绍了正则表达式的四大核心功能:匹配、切割、替换和获取。通过实例演示了如何使用Java进行手机号验证、字符串切割、重复字符替换及特定模式的字符串获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

正则是专门针对字符串的,有以下功能
1:匹配 :实际上使用的是String的 boolean matches(String regex)方法

2:切割: 实际上使用的是String的 String[] split(String regex)方法

3:替换: 实际上使用的是String replaceAll(String regex, String replacement) 把字符串中符合正则的字符串替换为第二参数接收的字符串

4:获取: 从一个字符串中得到我们需要的内容

import java.util.*;
import java.util.regex.*;
class Demo7 
{
	public static void main(String[] args) 
	{
		//match();
		//splits();
		//tiHuan();
		huoQu();
	}

	//4:获取
	public  static void huoQu()
	{
		String ss = "zhu yi le,ming tian fang jia";//获取到由4个字母构成的单词
		//定义获取的内容符合的正则表达式
		String regex="[a-z]{4}";

		//把正则表达式编译成Pattern类型的对象
		Pattern pattern = Pattern.compile(regex);

		//Pattern本身不具备从字符串获取内容的功能,所以需要使用Pattern对象得到Matcher对象
		//Matcher对象具备获取的功能
		Matcher matcher = pattern.matcher(ss);

		//使用Matcher的方法来获取内容
		//boolean boo = matcher.find();//先让Matcher对象去找,如果找到了返回true
		//if(boo)
		   //System.out.println(matcher.group());//再得到Matcher对象找到的内容
		while(matcher.find())
		{
			System.out.println(matcher.group());
		}
	}

	//3:替换
	public static void tiHuan()
	{
		String str1="zhangsan&&&&&&lisi*****wangwu######zhaoliu%%%%%%liuneng";
		String ss = str1.replaceAll("(.)\\1+","$1");// $1表示取第一组的值
		System.out.println(ss);

		String str2="zhangsan293743423434lisi5675756767567676wangwu982345678zhaoliu2345liuneng";
		String ss2 = str2.replaceAll("\\d{6,}","*******");
		System.out.println(ss2);

		String str3="13838384381";
		String ss3 = str3.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
		System.out.println(ss3);

	}

    //2:切割
	public static void splits()
	{
		//String str1="zhangsan.lisi.wangwu.zhaoliu.liuneng";
		//String regex="\\.";

		//String str1="zhangsan    lisi      wangwu   zhaoliu liuneng";
		//String regex=" +";

		String str1="zhangsan&&&&&&lisi*****wangwu######zhaoliu%%%%%%liuneng";
		//括号中的点表示任意字符,后面的\\1表示取第一个括号匹配的内容,后面的加号表示匹配1次或1次以上
		//二者加在一起就是某个字符重复两次或两次以上
		String regex="(.)\\1+"; //分组


		String[] arr = str1.split(regex);
		for(String ss:arr)
		{
			System.out.println(ss);
		}
	}
	//1:匹配
	public static void match()
	{
		//验证手机号是否合法
		String phone="13838384381";
		String regex="1[345789]\\d{9}";

		System.out.println(phone.matches(regex));
	}
}

总结
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值