正则表达式的学习

正则表达式

概要

基本上java所有的正则表达式都可以需要转义

一丶基础

\d表示数字 如果我们只想匹配0~9这样的数字,可以用\d匹配

String regex = "\\d\\d\\d\\d";
System.out.println("2222".matches(regex));
System.out.println("2A22".matches(regex));

.表示所有通配符

 String re3 = "a.c"; // 对应的正则是a\&c
System.out.println("a&c".matches(re3));
        System.out.println("a-c".matches(re3));
System.out.println("a&&c".matches(re3));
System.out.println("a@c".matches(re3));
System.out.println("a_c".matches(re3));
System.out.println("a c".matches(re3));

\w可以匹配一个字母、数字或下划线,w的意思是word

String re3 = "a\\wc";
System.out.println("a&c".matches(re3));
System.out.println("a-c".matches(re3));
System.out.println("a&&c".matches(re3));
System.out.println("a@c".matches(re3));
System.out.println("a c".matches(re3));
System.out.println("aac".matches(re3));
System.out.println("a2c".matches(re3));
System.out.println("a_c".matches(re3));

\s可以匹配一个空格字符,注意空格字符不但包括空格,还包括tab字符(在Java中用\t表示)。例如,a\sc可以匹配

用\d可以匹配一个数字,而\D则匹配一个非数字

重复匹配

修饰符可以匹配任意个字符,包括0个字符。我们用A\d可以匹配:

A:因为\d可以匹配0个数字;
A0:因为\d
可以匹配1个数字0;
A380:因为\d*可以匹配多个数字380。

+可以匹配至少一个字符。我们用A\d+可以匹配:

A0:因为\d+可以匹配1个数字0;
A380:因为\d+可以匹配多个数字380。
但它无法匹配"A",因为修饰符+要求至少一个字符。

?可以匹配0个或一个字符。我们用A\d?可以匹配:

A:因为\d?可以匹配0个数字;
A0:因为\d?可以匹配1个数字0。
但它无法匹配"A33",因为修饰符?超过1个字符就不能匹配了。

修饰符{n}就可以。A\d{3}可以精确匹配:

A380:因为\d{3}可以匹配3个数字380。

修饰符{n,m}就可以。A\d{3,5}可以精确匹配:

A380:因为\d{3,5}可以匹配3个数字380;
A3800:因为\d{3,5}可以匹配4个数字3800;
A38000:因为\d{3,5}可以匹配5个数字38000。
如果没有上限,那么修饰符{n,}就可以匹配至少n个字符。

如下图

总结

复杂的

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值