我有以下格式的文本:
section name 1:
this text goes into the first section
section name 2:
this text goes into the second section
等等,
其中节名称是任意短语,并且节内容将包含除节名称之外的自由文本。我需要将此文本拆分为类型的对象对(部分名称、部分文本)。
是否有有效的正则表达式或其他推荐的方法来执行此操作?
谢谢。 -拉吉
最佳答案
这取决于文档的结构。例如,每个部分是否都有空行?如果是这样,那么只需逐行扫描并以这种方式构造您的对象就会很容易。
List<Section> sections = new ArrayList<Section>();
String temp = null;
String line = null;
int lineNumber = 0;
while ((line = br.readLine()) != null) {
lineNumber++;
if (lineNumber % 2 == 0) {
// Section Text
sections.add(new Section(temp, line);
}
else {
// Section Name
temp = line;
}
}
那么您的部分可能是:
public class Section {
private final String name;
private final String text;
public Section(String name, String text) {
this.name = name;
this.text = text;
}
}
关于部分名称/内容文本需要 Java 文本解析帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3674245/