正则表达式在Java中的应用

正则表达式在Java中的应用

正则表达式其实不是Java中所独有的技术,它可以运用在很多地方比如html5中就可以使用,这里来简单描述一下正则表达式在Java中的应用

字符串匹配操作----字符串的matches()方法

注意: 字符串的匹配操作必须是完全匹配

public class Text01 {
public static void main(String[] args) {
	String src = "aaaxyz123aaa";
	String regex = "a{3}\\w{3}\\d{3}a{3}";
	System.out.println(src.matches(regex)); 
	}
}

代码运行结果为true

字符串替换操作----字符串的replaceAll()和replaceFirst()方法

注意: 只要字符串中有部分匹配成功即可执行替换操作

public class Text02 {
	public static void main(String[] args) {
	String src = "aaaxyz123aaa";
	String regex = "a{3}";
	System.out.println(src.replaceAll(regex, "X"));
	System.out.println(src.replaceFirst(regex, "X"));
	}
}

代码运行结果为:

Xxyz123X
Xxyz123aaa

字符串分割-----split() 方法

注意:字符串分割是将字符串变为空字符,然后再用逗号隔开,换句话说就是占了两个空

public class Text03 {
public static void main(String[] args) {
	String src = "aaa253xyz123aaa";
	String regex = "\\d{3}";
	String[] strs = src.split(regex);
	System.out.println(Arrays.toString(strs));
}
}

代码运行结果为:

[aaa, xyz, aaa]

字符串查找操作-----Pattern和Matcher

Pattern: 正则表达式对象

Matcher: 匹配器对象

public class Text04 {
public static void main(String[] args) {
		// 将正则表达式字符串编译成正则表达式对象
		Pattern p = Pattern.compile(regex);
		// 通过正则表达式对象获取匹配器对象
		Matcher m = p.matcher(src);
		boolean matches2 = m.matches();
		System.out.println(matches2);
}
}

代码结果为true

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值