gmhk
gmhk

Reputation: 15940

How can I split a string into meaningful tokens?

I need a better way of splitting the following string. I am not sure how to identify a substring and assign it to the correct variable:

at Manchester (Old Trafford) 24/8/1972 England won by 6 wickets [35 balls remaining]

I wanted to split the above string and assign substrings to different variables.

Venue --> Manchester (Old Trafford)
Date --> 24/8/1972
Result --> England won by 6 wickets  [35 balls remaining]

I tried StringTokenizer, but I felt it was too much work to get the assignment as above, and moreover it is too complex. When I used StringTokenizer I got the following substrings:

at Manchester
(Old
Trafford)
24/8/1972
England
won
by
6
wickets
[35
balls
remaining]

Please suggest any better ways of doing it.

Upvotes: 2

Views: 299

Answers (1)

erickson
erickson

Reputation: 269667

If all of the strings have the same format (venue, slash-separated date, result), you could use a regular expression.

Pattern p = Pattern.compile("(.+) (\\d+/\\d+/\\d+) (.+)");
Matcher m = p.matcher(record);
if (!m.matches()) 
  throw new IllegalArgumentException("Invalid record format.");
String venue = m.group(1);
String date = m.group(2);
String result = m.group(3);
...

This assumes that the venue will never contain a substring that looks like a date.

Upvotes: 3

Related Questions