当前位置: 首页 > news >正文

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

相关文章:

  • 1047. 删除字符串中的所有相邻重复项
  • 线性代数 第二章 矩阵
  • MyBatis 动态 SQL
  • 数据结构——基于顺序表实现通讯录
  • Kafka基本原理、生产问题总结及性能优化实践 | 京东云技术团队
  • YOLO算法改进6【中阶改进篇】:depthwise separable convolution轻量化C3
  • JAVA整理学习实例(一)面向对象
  • centos 搭建 zookeeper 高可用集群
  • AI:48-基于卷积神经网络的气象图像识别
  • Web测试是什么,有何特点?
  • SAP ABAP基础语法-TCODE学习(六)
  • 操作系统的线程模型
  • 用前端框架Bootstrap和Django实现用户注册页面
  • k8s 资源预留
  • Python+pytest+requests 自动化测试框架
  • SQL Server2000mdf升级SQL Server2005数据库还原
  • 亲测 IDEA Pycharm 全家桶 自动重置免费30天
  • 【Redis】Java连接Redis及Java操作Redis常用数据类型
  • memtest86 prosite v10.6
  • 电脑如何录制小视频
  • 日本农林水产大臣因不当“大米言论”引咎辞职
  • 演员朱媛媛去世,其丈夫辛柏青发讣告
  • 上海婚登人聂晶:见证爱情故事开启,也向长久婚姻致敬
  • 藤井树与藤井树:岩井俊二式的爱情,情书的三重生命
  • 遇见东方:18世纪俄罗斯宫殿中的“中国风”
  • 总书记回信二周年之际,上海如何将垃圾分类深度融入城市发展?