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\n ###第4章ccc\n ###第2章bbb\n ";
        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


 

相关文章:

  • 2021-12-09
  • 2021-12-08
  • 2022-12-23
  • 2022-12-23
  • 2021-12-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2023-01-03
  • 2021-11-29
  • 2021-11-06
  • 2022-12-23
  • 2021-09-26
相关资源
相似解决方案