简体   繁体   中英

Java String parsing including line break and regular expression

I am parsing file having values

kv {
  key "val1" 
  data "10"
}
kv {
  key "val2"
  data "20"
}
kv {
  key "val3"
}


Pattern p = Pattern.compile("\\s+key.+");

    Scanner sc = new Scanner(new File("kv.txt"));
    while (sc.hasNextLine()) {
        sc.nextLine();
        String line = sc.findInLine(p);

        if (line != null) {
            System.out.println(line);
        }
    }

Above code is picking fine all of the lines having value "key" but in some cases i am getting data which also have "data" elements as shown above in first two records. Wondering what regular expression i should be passing to Pattern.compile method that picks data till end braces - "}" of kv element.

Out put i am expecting is -> key "val1" data "10" AND key "val2" data "20" for first two kv records (string containing 4 substrings) and for the last one -> key "val3" only.

Try using \\s+key.+\\s.+

Demo here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM