[英]Java String Split / parsing issue using regular expression
I have Stream of String data which could have value 我有可能有价值的String流数据
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....
All i am interested is value of key, which are val1, val2, val3.... 我唯一感兴趣的是key的值,分别是val1,val2,val3 ....
I am using scanner as shown below, 我正在使用扫描仪,如下所示,
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];
}
This code is working fine when file is started with "kv {" but in above case when file is started with below mention value, parser is giving error. 当文件以“ kv {”开头时,此代码可以正常工作,但在上述情况下,当文件以以下提及的值开头时,解析器给出了错误。
system_id "2.2.2.1"
component_id 6
sequence_number 11
timestamp 1459202982
Any idea how can i skip this block of data? 知道如何跳过该数据块吗?
Note: This block of data could come occasionally after some "kv { }" tags, all i need is to ignore it whenever it comes. 注意:此数据块有时可能会在某些“ kv {}”标签之后出现,我需要的是在它出现时就忽略它。
Why dont you take just the interesting line? 你为什么不走有趣的路线呢?
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);
}
}
}
}
Please keep in mind that the file mentioned above is just my own test file. 请记住,上述文件只是我自己的测试文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.