关于Java中的正则表达式匹配
正则简单示例:
在线正则表达式网址:https://any86.github.io/any-rule/
java.util.regex是一个用正则表达式所订制的模式来对字符串进行匹配工作的类库包。它包括两个类:
Pattern:Pattern是一个正则表达式经编译后的表现模式
Matcher:Matcher对象是一个状态机器,它依据Pattern对象做为匹配模式对字符串展开匹配检查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public static void main(String[] args) { /*定义要进行验证的手机号码*/ String cellPhoneNumber = "15817784252" ; /*定义手机号码正则*/ String phoneRegex = "^(?:(?:\\+|00)86)?1(?:(?:3[\\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\\d])|(?:9[189]))\\d{8}$" ; /* 第一种:使用String类 说明此字符串是否与给定的正则表达式匹配。 参数: regex–此字符串要与之匹配的正则表达式 返回值: 当且仅当此字符串与给定正则表达式匹配时为true */ boolean stringMatches = cellPhoneNumber.matches(phoneRegex); System. out .println( "使用String类进行比较结果:" + stringMatches); /*第二种:使用Pattern * 将给定的正则表达式编译为模式。 * 参数: regex–要编译的表达式 * 返回值: 已编译为模式的给定正则表达式 * */ Pattern pattern = Pattern.compile(phoneRegex); /*创建一个匹配器,该匹配器将根据此模式匹配给定的输入。 参数: 输入–要匹配的字符序列*/ Matcher matcher = pattern.matcher(cellPhoneNumber); /*字符串是否与正则表达式相匹配*/ boolean patternMatches = matcher.matches(); System. out .println( "使用Pattern类的matcher进行比较结果:" + patternMatches); /*第三种:使用Pattern的两个参数构造器 * 参数1: 正则表达式 * 参数2: 要匹配的字符序列 * 返回值: 正则表达式是否与输入匹 * */ boolean constructorMatches = Pattern.matches(phoneRegex, cellPhoneNumber); System. out .println( "使用Pattern类的matcher重载进行比较结果" + constructorMatches); } |
判断字符串中是否包含数字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | // 判断字符串包含数字 方法一 public static boolean testIsNumMethodOne(String str) { boolean flag = false ; String numStr = "0123456789" ; for ( int i = 0 ; i < str.length(); i++) { String subStr = str.substring(i, i+ 1 ); if (numStr.contains(subStr)) { flag = true ; } } return flag; } // 判断字符串包含数字 方法二 public static boolean testIsNumMethodTwo(String str) { boolean flag = false ; Pattern pattern = Pattern.compile( "[0-9]+" ); Matcher matcher = pattern.matcher(str); if (matcher.find()) { flag = true ; } return flag; } // 判断字符串包含数字 方法三 public static boolean testIsNumMethodThree(String str) { boolean flag = false ; for ( int i = 0 ; i < str.length(); i++) { char c = str.charAt(i); if (c > 48 && c < 57 ) { flag = true ; } } return flag; } // 判断字符串包含数字 方法四 public static boolean testIsNumMethodFour(String str) { boolean flag = false ; for ( int i = 0 ; i < str.length(); i++) { char c = str.charAt(i); if (Character.isDigit(c)) { flag = true ; } } return flag; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话