【问题标题】:Java String Split / parsing issue using regular expression使用正则表达式的 Java 字符串拆分/解析问题
【发布时间】:2016-04-07 17:29:59
【问题描述】:

我有可能有价值的字符串数据流

system_id "2.2.2.1"
component_id 6
sequence_number 11
timestamp 1459202982

kv {
  key "val1"
}
kv {
  key "val2"
}
kv {
  key "val3"
}

system_id "2.2.2.1"
component_id 6
sequence_number 15
timestamp 1459202982

kv {
  key "val4"
}
kv {
  key "val5"
} and so on....

我感兴趣的是键的值,它们是 val1, val2, val3....

我正在使用如下所示的扫描仪,

scan = new Scanner(new File("kvfiles/file1")).useDelimiter("\\s+kv\\s+\\{\\s+");  //To ignore any thing before "kv"

while (scan.hasNext()) {
                String str = scan.next();
                finalString = str.split("\\s+\\}")[0];
}

当文件以“kv {”启动时,此代码工作正常,但在上述情况下,当文件以以下提及的值启动时,解析器给出错误。

    system_id "2.2.2.1"
    component_id 6
    sequence_number 11
    timestamp 1459202982

知道如何跳过这个数据块吗?

注意:这个数据块偶尔会出现在一些“kv { }”标签之后,我只需要在它出现时忽略它。

【问题讨论】:

  • 请提供有关错误的详细信息。
  • this demo 是否按预期工作?

标签: java regex parsing java.util.scanner


【解决方案1】:

你为什么不选择有趣的路线?

public class Test {

    public static void main(String[] args) throws FileNotFoundException {
        Pattern p = Pattern.compile("\\s+key.+");

        Scanner sc = new Scanner(new File("src/main/resources/test.txt"));
        while (sc.hasNextLine()) {
            sc.nextLine();
            String theLineYouWant = sc.findInLine(p);
            // scnn this line again here
            if (theLineYouWant != null) {
                System.out.println(theLineYouWant);
            }
        }
    }
}

请记住,上面提到的文件只是我自己的测试文件。

【讨论】:

  • 此模式未编译线程“main”中的异常 java.util.regex.PatternSyntaxException: Unknown character property name {+} near index 3 ^\p+key.+$ ^
  • 在遇到“}”之前是否可以选择等于所有事物的LineYouWant?这也将涵盖 kv { key "val3" data "53" } 的情况
猜你喜欢
  • 1970-01-01
  • 2011-07-18
  • 1970-01-01
  • 2011-10-16
  • 1970-01-01
  • 2010-11-22
  • 1970-01-01
相关资源
最近更新 更多