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
相关推荐
间彧2 小时前
SimpleDateFormat既然不推荐使用,为什么java 8+中不删除此类
java
间彧2 小时前
DateTimeFormatter相比SimpleDateFormat在性能上有何差异?
java
间彧2 小时前
为什么说SimpleDateFormat是经典的线程不安全类
java
MacroZheng3 小时前
横空出世!MyBatis-Plus 同款 ES ORM 框架,用起来够优雅!
java·后端·elasticsearch
用户0332126663673 小时前
Java 查找并替换 Excel 中的数据:详细教程
java
间彧3 小时前
ThreadLocal实现原理与应用实践
java
若水不如远方3 小时前
Netty的四种零拷贝机制:深入原理与实战指南
java·netty
用户7493636848433 小时前
【开箱即用】一分钟使用java对接海外大模型gpt等对话模型,实现打字机效果
java
SimonKing4 小时前
一键开启!Spring Boot 的这些「魔法开关」@Enable*,你用对了吗?
java·后端·程序员