Reputation: 160
I need to parse this into strings in the most efficient way. I currently have this line
D[date-string] T[time-string] N[name-string] M[message-string]
Needs to be parsed into four strings respectively,
private String time; //would equal time-string
private String date; //would equal date-string
private String name; //would equal name-string
private String message; //would equal message-string
Is there an easy way to do this?
Upvotes: 2
Views: 47
Reputation: 160
Wow, easy easy easy!
D[(.*?)] for the date!
https://regex101.com/r/vM0yW8/1
Upvotes: 0
Reputation: 8200
You can use regex and groups to match and extract that kind of data: For example, something like:
Pattern p = Pattern.compile("D(\\w+) T(\\w+) N(\\w+) M(\\w+)");
Matcher m = p.matcher(yourString);
if (m.matches()){
String d = m.group(1);
String t = m.group(2);
String n = m.group(3);
String w = m.group(4);
}
The patterns within the parentheses are saved into groups, which you can extract after the match (it starts with 1, since 0 is the whole match). You have then to change that to the characters and patterns you want to accept.
Upvotes: 1
Reputation: 625
The below logic will work. How regix will hep not sure. But the below code will also be ok as it is not looping and anything so i think it will could be the optimum solution.
String s = "D[date-string] T[time-string] N[name-string] M[message-string]";
String[] str = s.split(" ");
String date = str[0].substring(str[0].indexOf("[")+1, str[0].lastIndexOf("]")); //would equal time-string
String time=str[1].substring(str[1].indexOf("[")+1, str[1].lastIndexOf("]")); //would equal date-string
String name=str[2].substring(str[2].indexOf("[")+1, str[2].lastIndexOf("]")); //would equal name-string
String message=str[3].substring(str[3].indexOf("[")+1, str[3].lastIndexOf("]"));
Upvotes: 0
Reputation: 161
I'm not sure if I've understood you but looks like using regular expression is the easiest way to do this kind of parsing.
Upvotes: 0