部分名称/内容文本需要 Java 文本解析帮助

标签 java regex parsing

我有以下格式的文本:

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/

相关文章:

java - Ant exclusfile 编译java文件

java - 将 PHP 转换为 Java

c# - 正则表达式 c# 属性到 typescript 字段

android - 如何使用dom和saxparser解析android中的本地xml文件?

java - 从无状态 Bean 返回有状态 Java Bean?

java - 在路径中向后退一步的 Xpath 查询

regex - 如何在这个给定的场景中应用惰性量词?

iphone - 使用 REGEX 解析 html NSString

objective-c - 将 URL 解析到服务器时无法处理方括号 (=[])

c# - C#中的解析树