Java 正则表达式数字篇

如果需要根据特定的规则来表示一组字符串,则用正则表达式。正则表达式可以用字符串来描述规则,并用来匹配字符串

Java 提供了标准库 java.util.regex ,可以很方便的使用正则表达式。

如果正则表达式有特殊字符,那就需要用 \ 转义,后续会提到。

数字

匹配数字

\d 可以匹配一位数字,写法是 \\d ,

复制代码
String regex1 = "\\d\\d\\d";
System.out.println("110".matches(regex1)); // true
System.out.println("119".matches(regex1)); // true
System.out.println("120".matches(regex1)); // true
System.out.println("1200".matches(regex1)); // false
System.out.println("12F".matches(regex1)); // false

是否是 11 位数字,常用场景是判断手机号,

复制代码
String regex2 = "\\d{11}";
System.out.println("12345678900".matches(regex2));// true
System.out.println("123456789001".matches(regex2));// false
System.out.println("1234567890a".matches(regex2));// false
System.out.println("A2345678900".matches(regex2));// false

匹配非数字

\D 匹配一位非数字,写法是 \\D

复制代码
        String regexD = "\\D\\D";
        System.out.println("66".matches(regexD));// false
        System.out.println("1*".matches(regexD));// false
        System.out.println("1@".matches(regexD));// false
        System.out.println("1#".matches(regexD));// false
        System.out.println("$$".matches(regexD));// true

匹配0-9的数字

[0-9] 可以匹配一位数字,

复制代码
        String regexd09 = "[0-9][0-9]";
        System.out.println("11".matches(regexd09));// true
        System.out.println("110".matches(regexd09));// false
        System.out.println("1A".matches(regexd09));// false
        System.out.println("AA".matches(regexd09));// false

扩展, 匹配 5-8 的数字用 [5-8] ,

复制代码
        String regexd58 = "[5-8][5-8]";
        System.out.println("55".matches(regexd58));// true
        System.out.println("88".matches(regexd58));// true
        System.out.println("66".matches(regexd58));// true
        System.out.println("59".matches(regexd58));// false
        System.out.println("48".matches(regexd58));// false
相关推荐
TT哇44 分钟前
【Java EE初阶】计算机是如何⼯作的
java·redis·java-ee
Fireworkitte7 小时前
Apache POI 详解 - Java 操作 Excel/Word/PPT
java·apache·excel
weixin-a153003083167 小时前
【playwright篇】教程(十七)[html元素知识]
java·前端·html
DCTANT8 小时前
【原创】国产化适配-全量迁移MySQL数据到OpenGauss数据库
java·数据库·spring boot·mysql·opengauss
Touper.8 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
黄雪超8 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice8 小时前
对象的finalization机制Test
java·开发语言·jvm
望获linux10 小时前
【实时Linux实战系列】CPU 隔离与屏蔽技术
java·linux·运维·服务器·操作系统·开源软件·嵌入式软件
JosieBook10 小时前
【Java编程动手学】使用IDEA创建第一个HelloJava程序
java·开发语言·intellij-idea
Thomas_YXQ10 小时前
Unity3D DOTS场景流式加载技术
java·开发语言·unity