zoukankan      html  css  js  c++  java
  • 分隔指定内容,提取章节数

    package push;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class MatchContent {
        public static void main(String[] args) {
            String  split = "###第\d+章";
            String content = "###第1章aaa
     ###第4章ccc
     ###第2章bbb
     ";
            Pattern p = Pattern.compile(split);
            Matcher m = p.matcher(content);
            int tempStart = 0;
            int tempEnd = 0;
            int tempChapterId = 0;
            Map<Integer,String> chapterMap = new TreeMap<Integer, String>();
            if(m.find()) {
                tempStart = m.start();
                tempChapterId = Integer.valueOf(content.substring(m.start(),m.end()).replace("#", "").replace("第", "").replace("章", ""));
            }
            while(m.find()) {
                tempEnd=m.start();
                chapterMap.put(tempChapterId, content.substring(tempStart,tempEnd));
                tempStart = tempEnd;
                tempChapterId = Integer.valueOf(content.substring(m.start(),m.end()).replace("#", "").replace("第", "").replace("章", ""));
                
                
            }
            if(tempStart!=0) {
                chapterMap.put(tempChapterId, content.substring(tempStart));
            }
            
            for(Integer at:chapterMap.keySet()) {
                System.out.println("章节数:" + at + " 内容:" + chapterMap.get(at).replace("#", ""));
            }
        }
    }

    输出是

    章节数:1 内容:第1章aaa

    章节数:2 内容:第2章bbb

    章节数:4 内容:第4章ccc


  • 相关阅读:
    c++构造函数析构函数调用顺序
    c++隐藏实例
    c++子类和父类成员函数重名
    C++虚函数·
    c/c++字符数组和字符串大揭秘
    python 基础回顾 一
    python java scala 单例模式
    推荐一款好用并且免费的markdown软件 Typora
    java 的垃圾回收机制 【转】
    python的垃圾回收机制【转】
  • 原文地址:https://www.cnblogs.com/yanghuahui/p/3438460.html
Copyright © 2011-2022 走看看