i want write text file json file using regular expressions java.
meaning want text file containing this:
5.2 hello
sentence 1. sentence 2.
to become this:
{"chapter": "5.2", "title": "hello", "text": "sentence 1. sentence 2."}
i have code match fields in text file , output json, i'm not sure how break json sections need using regex.
i'm attempting this:
pattern p = pattern.compile((\d\.\d)(.*?)(?=\d\.\d|$)); matcher m = p.matcher(readfile(text)); while(m.find()) { obj.put("chapter", m.group()); system.out.println(obj);}
but outputs chapter field followed rest of text. i'm not sure how split data chapter, title , text fields.
input:
5.2 hello
sentence 1. sentence 2.
current output is:
{"chapter": "5.2 hello sentence 1. sentence 2."}
but need this:
{"chapter": "5.2", "title": "hello", "text": "sentence 1. sentence 2."}
any help?
i assume input format:
5.2 hello \n
whatever text...
your way of thinking correct. since want divide original text 3 sections. need make use of border between sections. example, "5.2" , "hello" have space (\s) in bewteen, "hello" has new line (or maybe space) before main text.
you can try:
pattern p = pattern.compile("(\\d+\\.\\d+)\\s+(.*?)\\n(.*$)"); matcher m = p.matcher(text); if(m.find()) { obj.put("chapter", m.group(1)); obj.put("title", m.group(2)); obj.put("text", m.group(3)); system.out.println(obj); }
your previous way of using group incorrect, because number of groups depends on how many pairs of bracket have pattern.compile(). since have 3 groups in total, use index value.
note: group(0) whole thing, first group accessed index 1.
Comments
Post a Comment