Praneel PIDIKITI
Praneel PIDIKITI

Reputation: 19537

parse String into tokens based on the positions

I have this string

"Name, Show starts on 14/08/09, your ticket is booked on 14/08/09"

In this string i want to get the value StartDate, bookedDate and nameofthePerson as a individual tokens.This should work with all the strings in the same format

How can i parse them in java ?

Upvotes: 0

Views: 638

Answers (3)

Matthew Gilliard
Matthew Gilliard

Reputation: 9498

I expect people will be very eager to recommend regex for this, but I don't think that they always offer the best solution. They can be hard to read, and harder to debug. So as an alternative, I suggest String.split():

    String line = "Name, Show starts on 14/08/09, your ticket is booked on 14/08/09";
    String[] parts = line.split("[ ,]"); // ie split on comma or space

    String name = parts[0];
    String showDate = parts[5];
    String bookDate = parts[12];

    System.out.println(name + ":" + showDate + ":" + bookDate);

Upvotes: 1

Thomas
Thomas

Reputation: 88747

So if the format is the same, you might use a regular expression and collect the values into groups.

Something like this:

String input = "Name, Show starts on 14/08/09, your ticket is booked on 14/08/09";
String regex = "([a-zA-Z \t]*),.*(\\d\\d/\\d\\d/\\d\\d),.*(\\d\\d/\\d\\d/\\d\\d)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher( input );
if( matcher.matches() && matcher.groupCount() == 4) //group 0 is always the entire expression
{
  String name = matcher.group(1);
  String startDate = matcher.group(2);
  String bookedDate = matcher.group(3);
}

Upvotes: 2

limc
limc

Reputation: 40176

How about this?

String s = "Name, Show starts on 14/08/09, your ticket is booked on 14/08/09";

String wordsPattern = "[\\w\\s]+";
String datePattern = "\\d{1,2}\\/\\d{1,2}\\/\\d{1,2}";
Pattern p = Pattern.compile(String.format("(%s),%s(%s),%s(%s)", wordsPattern, wordsPattern, datePattern, wordsPattern, datePattern));

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
Matcher m = p.matcher(s);
m.find();

String name = m.group(1);
Date startDate = sdf.parse(m.group(2));
Date bookedDate = sdf.parse(m.group(3));

System.out.println("name: " + name);
System.out.println("startDate: " + startDate);
System.out.println("bookedDate: " + bookedDate);

The result:-

name: Name
startDate: Wed Apr 08 00:00:00 CDT 2009
bookedDate: Wed Apr 08 00:00:00 CDT 2009

Upvotes: 0

Related Questions