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
相关推荐
蜗牛互联网24 分钟前
GPT-6 与 Intelligent UI:从回答到可审计操作的产品迁移
java·人工智能·后端
临床数据科学和人工智能兴趣组1 小时前
正则表达式的基础语法的基本符号
开发语言·人工智能·python·正则表达式·r语言·r语言-4.2.1·workbudyy
SL_staff1 小时前
运维救火实录:钉钉考勤API变更引发工资计算异常,我们用JVS-Logic可视化逻辑引擎实现分钟级热修复
java·mysql·全栈
SunnyDays10111 小时前
Java 查找并高亮 Word 文字:精确查找及正则表达式模糊查找
java·查找文字·word 文档·高亮文字·正则匹配查找·模糊查找
geats人山人海1 小时前
java 4继承
java·开发语言
众链网络2 小时前
Agent 的成本大头不在“写“,在“判断“:拆解专用决策模型的三层架构
java·开发语言·人工智能·微服务
周小董2 小时前
[1371]jdk管理工具
java·开发语言
青春逝如流水2 小时前
Java 中线程的创建方式:从基础到现代
java·开发语言·多线程·ai文章
Peregrine93 小时前
C++ - > 类和对象
java·c++·算法
2501_933923253 小时前
SpringCloud组件:Eureka服务注册与发现
java·开发语言·后端·spring cloud·eureka