此篇文章是记录我在学习java正则表达式时候学到的和遇到的坑。
先来说说 matcher 里面的三个方法(取的结果以group()方法为例子)
好了上测试代码:
package com.wjj.utils; import java.util.regex.matcher; import java.util.regex.pattern; /** * @author 作者 : 榨菜哥 * @version 创建时间:2016年8月18日 上午8:47:58 * 类说明:正则表达式的练习 */ public class regex { //find方法测试 public static void find(string html) { string regex = "\\d\\d\\d"; pattern pattern = pattern.compile(regex, pattern.case_insensitive); matcher matcher = pattern.matcher(html); system.out.print("find():"); if (matcher.find()) { system.out.println(matcher.group()); } } //matches方法测试 public static void matches(string html) { string regex = "^\\w\\d\\d\\d"; pattern pattern = pattern.compile(regex, pattern.case_insensitive); matcher matcher = pattern.matcher(html); system.out.print("matches():"); if (matcher.matches()) { system.out.println(matcher.group()); } } //lookingat方法测试 public static void lookingat(string html) { string regex = "\\w\\d\\d"; pattern pattern = pattern.compile(regex, pattern.case_insensitive); matcher matcher = pattern.matcher(html); system.out.print("lookingat():"); if (matcher.lookingat()) { system.out.println(matcher.group()); } } public static void main(string[] args) { //find方法测试 find("a123b"); //matches方法测试 matches("a123"); //lookingat方法测试 lookingat("a123b"); } }
输出结果:
find():123
matches():a123
lookingat():a12
小结:正则表达式本身并不难,平常使用的时候只要按照规则来写就好了。在学习中理解matches、find、和lookingat三个方法花了我比较长的时间,一直不能理解完全匹配和部分匹配是什么意思,最后还是在stackoverflow上找到了想要的答案。
以上是个人学习的理解,有不对之处,希望给予指点。
(补充:正则表达式pattern如果调用多次容易出问题,比如内存溢出,因为pattern每执行一次就编译一次正则表达式,因此建议将需要的正则表达式进行预编译。)
正则表达式学习教程: ,文中作者写得挺详细的,并且通俗易懂。
总结
以上所述是小编给大家介绍的java正则相关的pattern和matcher类及遇到的坑,希望对大家有所帮助
如对本文有疑问, 点击进行留言回复!!
生成模型——NVAE: A Deep Hierarchical Variational Autoencoder——arxiv2020.07
Element-ui 表格 (Table) 组件中动态合并单元格
【leetcode C语言实现】剑指 Offer 19. 正则表达式匹配
Linux - 基础正则表达式、扩展正则表达式、grep使用正则表达式
网友评论