0

假设您有一个包含以下内容的 txt 文件:

<tag><info>George 34 Washington Professor 

Alexander 22 London Student

Jessica 18 Moscow Student<info><tag>

当您使用 readline 从文本文件中提取参数时,如何忽略标签?

4

2 回答 2

1

正则表达式有什么问题?

Scanner s = new Scanner(new File("file.txt"));
while (s.hasNext())
{
  String line = s.nextLine().replaceAll("<[^>]*>", "");
  System.out.println(line);
}

但是,上述方法不适用于跨多行拆分的标签,您必须做一些更复杂的事情:

Scanner s = new Scanner(new File("file.txt"));
boolean inTag = false;
while (s.hasNext())
{
  String lineTemp = s.nextLine();
  for (char c: line.toCharArray())
  {
    switch (c)
    {
      case '<': inTag = true; break;
      case '>': inTag = false; break;
      default:
        if (!inTag)
          sb.append(c);
    }
  }
  String line = sb.toString();
  System.out.println(line);
}

除了指示标签的开始和结束之外,上述任何一个都没有说明出现<和任何地方。>

于 2013-03-02T22:28:36.437 回答
0

您可以使用正则表达式从行中删除标签

String line = line.replaceAll("<.+?>", "");
于 2013-03-03T02:55:13.127 回答