2019独角兽企业重金招聘Python工程师标准>>>

Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
public Matcher appendReplacement(StringBuffer sb, String replacement) {// If no match, return errorif (first < 0) //first表示正则匹配到的第一个字符在字符串(one cat two cats in the yard)中的下标throw new IllegalStateException("No match available");// Process substitution string to replace group references with groupsint cursor = 0; //当前操作字符在替代字符串(dog)中的下标StringBuilder result = new StringBuilder();//解析替代字符串的结果//开始解析while (cursor < replacement.length()) {char nextChar = replacement.charAt(cursor);//获取当前操作的字符if (nextChar == '\\') {//如果当前操作的字符是转义符号//下面就是解析replacement转义符号的过程cursor++;//跳过转义符号if (cursor == replacement.length())throw new IllegalArgumentException("character to be escaped is missing");nextChar = replacement.charAt(cursor);//获取转义符号后面的字符result.append(nextChar);//添加到resultcursor++;//下标加一  回到上面while循环} else if (nextChar == '$') {//如果当前操作的字符是$//下面就是解析replacement中如何引用捕获组的内容// Skip past $cursor++;// 跳过$符号// Throw IAE if this "$" is the last character in replacementif (cursor == replacement.length())throw new IllegalArgumentException("Illegal group reference: group index is missing");nextChar = replacement.charAt(cursor);//获取$后面的字符int refNum = -1;if (nextChar == '{') {//解析命名捕获组cursor++;StringBuilder gsb = new StringBuilder();//提取${groupname}中的groupname字符串while (cursor < replacement.length()) {nextChar = replacement.charAt(cursor);//获取{的下一个字符if (ASCII.isLower(nextChar) ||ASCII.isUpper(nextChar) ||ASCII.isDigit(nextChar)) {//这个字符是大小写的字母或数字gsb.append(nextChar);cursor++;} else {//不是的话退出循环  后面判断是不是这个字符是不是},不是就抛异常break;}}if (gsb.length() == 0)throw new IllegalArgumentException("named capturing group has 0 length name");if (nextChar != '}')throw new IllegalArgumentException("named capturing group is missing trailing '}'");String gname = gsb.toString();// group nameif (ASCII.isDigit(gname.charAt(0))) //group name 不能以数字开头throw new IllegalArgumentException("capturing group name {" + gname +"} starts with digit character");if (!parentPattern.namedGroups().containsKey(gname)) //捕获组的Map中要有相对应的group namethrow new IllegalArgumentException("No group with name {" + gname + "}");refNum = parentPattern.namedGroups().get(gname);//获取在捕获组中是第几个 begin with 1cursor++;} else {// The first number is always a grouprefNum = (int)nextChar - '0'; //减去字符0的ASCII码if ((refNum < 0)||(refNum > 9))//不是数字的话 抛异常throw new IllegalArgumentException("Illegal group reference");cursor++;// Capture the largest legal group stringboolean done = false;while (!done) {if (cursor >= replacement.length()) {//当前操作是最后一个字符或者后面已经没有字符了break;}int nextDigit = replacement.charAt(cursor) - '0';//减去字符0的ASCII码if ((nextDigit < 0)||(nextDigit > 9)) { // not a number  数字后面不是数字了break;}int newRefNum = (refNum * 10) + nextDigit;//还是数字  乘10累加上去if (groupCount() < newRefNum) {//累加后发现数值大于捕获组的总数done = true;//结束返回refNum中的值} else {//累加后的数值小于或等于捕获组总数  继续循环下一个字符refNum = newRefNum;/cursor++;}}}// Append groupif (start(refNum) != -1 && end(refNum) != -1)result.append(text, start(refNum), end(refNum));   //获取对应捕获组的开始下标和结束下标} else {//正常字符直接添加result.append(nextChar);cursor++;}}// Append the intervening textsb.append(text, lastAppendPosition, first);//上一次添加位置到捕获组第一个字符位置// Append the match substitutionsb.append(result);//添加解析后的替代字符串lastAppendPosition = last;return this;
}

转载于:https://my.oschina.net/zhuqianli/blog/1535390

Java Matcher源码学习记录相关推荐

  1. Spark-Core源码学习记录 3 SparkContext、SchedulerBackend、TaskScheduler初始化及应用的注册流程

    Spark-Core源码学习记录 该系列作为Spark源码回顾学习的记录,旨在捋清Spark分发程序运行的机制和流程,对部分关键源码进行追踪,争取做到知其所以然,对枝节部分源码仅进行文字说明,不深入下 ...

  2. JAVA JDK 源码学习

    JAVA JDK 源码学习 ,以1.8为例,按照下面图片顺序依次学习: applet ,awt,beans,io,lang,math,net,nio,rmi,security,sql,text,tim ...

  3. java Integer 源码学习

    转载自http://www.hollischuang.com/archives/1058 Integer 类在对象中包装了一个基本类型 int 的值.Integer 类型的对象包含一个 int 类型的 ...

  4. 【开源与项目实战:开源实战】77 | 开源实战一(下):通过剖析Java JDK源码学习灵活应用设计模式

    上一节课,我们讲解了工厂模式.建造者模式.装饰器模式.适配器模式在 Java JDK 中的应用,其中,Calendar 类用到了工厂模式和建造者模式,Collections 类用到了装饰器模式.适配器 ...

  5. Java集合源码学习(四)HashMap

    一.数组.链表和哈希表结构 数据结构中有数组和链表来实现对数据的存储,这两者有不同的应用场景, 数组的特点是:寻址容易,插入和删除困难:链表的特点是:寻址困难,插入和删除容易: 哈希表的实现结合了这两 ...

  6. Java集合源码学习(五)几种常用集合类的比较

    这篇笔记对几个常用的集合实现,从效率,线程安全和应用场景进行综合比较. 1.ArrayList.LinkedList与Vector的对比 (1)相同和不同 都实现了List接口,使用类似. Vecto ...

  7. Java集合源码学习(4)HashSet

    1 概述 HashSet 是一个没有重复元素的集合.它的底层是由HashMap实现的,不保证元素的顺序.HashSet允许使用 null 元素. 截取一段源码: public class HashSe ...

  8. microsoft 的gpt2模型源码学习记录

    相关链接: gpt2论文传送门 microsoft Deepspeed gpt2源码传送 微软 Deepspeed 中集成的 gpt2 代码感觉比 huggingface 的代码可读性要强很多,这里只 ...

  9. java.lang 源码学习02 Comparable接口

    一. 前言 在Java集合框架里面,各种集合的操作很大程度上都离不开Comparable和Comparator,虽然它们与集合没有显示的关系,但是它们只有在集合里面的时候才能发挥最大的威力.下面是开始 ...

  10. Swoole源码学习记录(五)——锁和信号(二)

    Swoole版本:1.7.4-stable Github地址: https://github.com/LinkedDestiny/swoole-src-analysis 二.Mutex互斥锁 接下来是 ...

最新文章

  1. [php错误]PHP中Notice: unserialize(): Error at offset of bytes in on line 的解决方法
  2. htmlspecialchars() 函数把一些预定义的字符转换为 HTML 实体。
  3. 存储过程和函数——概述||创建存储过程||调用存储过程||查看存储过程||删除存储过程
  4. python执行系统命令后获取返回值的几种方式集合
  5. 为什么需要StringBuffer
  6. Boost 1.34.0 终于5.12发布了
  7. matlab图像的主视图,求助大佬【如用MATLAB实现满足投影关系的三视图】
  8. pytorch: 网络层参数初始化
  9. C++算法学习(力扣:859. 亲密字符串)
  10. 机械师电脑_必看!面对电脑玩游戏卡顿,需要做些什么?
  11. Angular.js 简单实现数字变汉字
  12. 色彩空间(CIE色度图,SRGB,AdobeRGB...)
  13. Udacity数据分析(入门)-探索美国共享单车数据
  14. exports is not defined
  15. UITableView 部分方法详解
  16. 第二章 源力、质量、能量
  17. 打开计算机桌面上没有跑哪里去了,Win8.1我的电脑图标跑哪去了怎么放桌面
  18. google的秘密入口+搜索技巧
  19. [Study]Vue
  20. 高德地图 坐标与地址

热门文章

  1. hibernate DetachedCriteria实现多表关联查询createAlias的使用
  2. 简单5步,释放Mac磁盘空间
  3. ArcGIS Desktop10.2与CityEngine2012兼容问题
  4. c#2.0语法新关键字 partial
  5. AtCoder Grand Contest 023
  6. Linux-文件目录命令
  7. 三级联动第二种方法 三级联动.html
  8. 51nod1417 天堂里的游戏
  9. 入侵感知系列之弱口令检测思路
  10. 2018-05-04 http入门