【问题标题】:Java seperate words and meanings from a fileJava 从文件中分离单词和含义
【发布时间】:2016-08-19 10:43:03
【问题描述】:

我需要将单词和含义从文件中分离出来,然后我想存储 sqlite (WORDS) 表中的每个单词及其在另一个 (MEANING) 表中的对应含义。

文件如下所示。

word 1
    explanation 1
    explanation 1
    explanation 1

    explanation 1
word 2
    explanation 2
    explanation 2

    explanation 2
    explanation 2
word 3
    explanation 3
    explanation 3
    explanation 3

    explanation 3
word 4
    explanation 4

    explanation 4

    explanation 4

现在的问题是我无法弄清楚如何将单词和含义分成 1 - 1 个对应关系。解释行之间的空格即使拆分后也应该存在。

这是我迄今为止尝试过的示例代码。

Scanner sc = new Scanner(file);
String abbr = "";
String exp = "";
String line;
while (sc.hasNext()) {
    if (!(line = sc.nextLine()).isEmpty() && !(line.startsWith("    "))) {
        abbr = line;
        //Debug
        System.out.println(abbr);
        printExp(exp);
        exp = "";
    } else if (line.isEmpty() || line.startsWith("  ")) {
        exp += line;
    }
}

用于调试目的的方法。

public static void printExp(String exp) {
    if (!exp.equals("")) {
        System.out.println(exp);
    }
}

您可能会想到任何其他简单的解决方案,例如通过正则表达式。 非常感谢您的帮助。

【问题讨论】:

  • "文件看起来像这样。"呃,不,那是图像。文本文件中会包含文本。
  • ...而且会更容易试验。
  • 好的。只是为了记住文件的布局。
  • ^(\w.*)((?:\n(?:$| ).*)*) 之类的东西可能会帮到你。 See it here at regex101.

标签: java regex split


【解决方案1】:

如果我理解正确,这可能对你有用:

^(\w.*)((?:\n(?:$|\W).*)*)

它捕获以单词字符开头的行。然后它会捕获以空格开头的任意数量的行,或者是空行。

See it here at regex101.

【讨论】:

  • 你做对了。你可以在上面的代码中使用它吗?谢谢
猜你喜欢
  • 2023-01-25
  • 2017-04-07
  • 2014-11-04
  • 1970-01-01
  • 2021-06-25
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
相关资源
最近更新 更多