2

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?

Daniel Mills
  • 160
  • 8
  • If you have a standard format for date, time, name & message then you can probably use regex and use `split` method in String class – Dhanush Gopinath Jul 14 '15 at 12:31

5 Answers5

1

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.

user140547
  • 7,750
  • 3
  • 28
  • 80
0

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.

Yogev Caspi
  • 151
  • 12
0

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("]"));
Kulbhushan Singh
  • 627
  • 4
  • 20
0

Take a look here and here, you will have to tune it accordingly.

Community
  • 1
  • 1
johndoe
  • 4,387
  • 2
  • 25
  • 40
0

Wow, easy easy easy!

D[(.*?)] for the date!

https://regex101.com/r/vM0yW8/1

Daniel Mills
  • 160
  • 8