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; MapchapterMap = new TreeMap (); 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