2

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.

erickson
  • 265,237
  • 58
  • 395
  • 493
gmhk
  • 15,598
  • 27
  • 89
  • 112
  • Perhaps you should explore a bit into Regular Expressions. – adarshr Mar 19 '12 at 16:36
  • 1
    One example input does not a specification make. Either say in plain English what the specification is (what pattern will the input follow?) or give more examples so that we can learn by example. – Mark Peters Mar 19 '12 at 16:36

1 Answers1

3

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.

erickson
  • 265,237
  • 58
  • 395
  • 493