Java 正则表达式数字篇

编程入门 行业动态 更新时间:2024-10-27 23:28:04

Java 正则表达式<a href=https://www.elefans.com/category/jswz/34/1771323.html style=数字篇"/>

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));// falseSystem.out.println("1*".matches(regexD));// falseSystem.out.println("1@".matches(regexD));// falseSystem.out.println("1#".matches(regexD));// falseSystem.out.println("$$".matches(regexD));// true

匹配0-9的数字

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

        String regexd09 = "[0-9][0-9]";System.out.println("11".matches(regexd09));// trueSystem.out.println("110".matches(regexd09));// falseSystem.out.println("1A".matches(regexd09));// falseSystem.out.println("AA".matches(regexd09));// false

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

        String regexd58 = "[5-8][5-8]";System.out.println("55".matches(regexd58));// trueSystem.out.println("88".matches(regexd58));// trueSystem.out.println("66".matches(regexd58));// trueSystem.out.println("59".matches(regexd58));// falseSystem.out.println("48".matches(regexd58));// false

更多推荐

Java 正则表达式数字篇

本文发布于:2023-11-16 16:44:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628197.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   正则表达式   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!