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


  • 相关阅读:
    Django模型层进阶
    Django模型层相关
    BOM与DOM
    JavaScript入门
    HTML基础
    子查询/联合分组/all与any/视图/事务
    表的查询
    mysql的多表关系
    Mysql基本操作
    Spider_基础总结2_Requests异常
  • 原文地址:https://www.cnblogs.com/yanghuahui/p/3438460.html
Copyright © 2011-2022 走看看