0

我有一个文本文件转储,需要将其转换为分隔文件。该文件包含一系列格式如下的“记录”(因为没有更好的词):

User: abc123 
Date: 7/3/12
Subject: the foo is bar
Project: 123456
Problem: foo bar in multiple lines of text
Resolution: foo un-barred in multiple lines of text

User: abc123 
Date: 7/3/12
Subject: the foo is bar
Project: 234567
Problem: foo bar in multiple lines of text
          which may include <newline> and 
          extend to multiple lines of text
Resolution: foo un-barred in multiple lines of text

...

现在,使用 Java,我使用 StringBuffer 逐行读取此文件,根据一系列if(inputLine.toLowerCase().startsWith("user:"))逻辑将行解析为单个字段,以将最终分隔行输出到文本文件。

但是,字段ProblemResolution是自由格式的,并且可能是多行的。我正在尝试做一些会创建两个字符串的事情:附加所有行之后Problem:并结束于,Resolution:并附加所有行之后开始Resolution:和结束于Form:

我已经查看了这个链接这个链接,这表明这StringBuilder可能是一种合适的方式来做到这一点......但是,我不太确定如何构建逻辑。

编辑: 因为我正在逐行阅读,所以我很难理解如何编码

<pseudocode>
If the line starts with "Problem" extract the charactes after "Problem" else
if the PRIOR line starts with "problem" and the current line doesnt start with "resolution" then append characters in line to prior line
etc.
</pseudocode>

但是,如果有第三行“问题......?我只是无法想象如何让它工作。

有什么想法或替代方法可以实现我想要的结果?

4

3 回答 3

2

嗨,如果我正确理解了您的问题,那么这些方面的东西应该可以工作:

    StringBuilder problemDesc = new String....;
    if(inputLine.toLowerCase().startsWith("problem:")){
       problemDesc.append(inputLine);
       while(!inputLine.toLowerCase().startsWith("resolution:"){
           //read next line into inputline;
           problemDesc.append(inputline);
       }
       //deal with problem description here and inputLine now has the line with
       //Resolution in it Repeat same logic for retrieving the resolution value
    }
于 2012-07-03T13:15:41.823 回答
2
StringBuilder problem;
StringBuilder resolution;

//...

// If the current line starts with "Problem: "
if(inputLine.toLowerCase().startsWith("Problem: ")) {
   // Continue appending to the string builder until the delimiting line is reached
   while(!inputLine.toLowerCase().startsWith("Resolution") {
      problem.append(inputLine);
   }
}

// Something similar for resolution
于 2012-07-03T13:17:13.903 回答
1

我将在这里大胆一点,并建议使用真正的解析器生成器,例如JavaCC

您在问题中提到只有两个字段是自由格式的,但也许将来可能会添加其他字段作为自由格式?当添加第三、第四或第 n 个特殊情况时,硬编码两个字段以不同方式处理可能会产生很多副作用。

JavaCC 将在运行时为您生成一个真正的解析器,而不需要任何额外的 jar,甚至更好的是,它允许您考虑您的解析规则,以便将来的特殊情况不会给您带来任何痛苦。

于 2012-07-03T13:20:53.557 回答