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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值