Fixed Formats: regexp and fmt.Sscanf
Sometimes a line has a fixed sentence shape, with a few values that change inside it:
KRL 07:15 Bogor -> Jakarta Kota (54 min)
Fields would split Jakarta Kota into two parts. For shapes like this a regular expression fits better: you write the pattern once, then pick out the captured parts.
regexp with capture groups
var tripLine = regexp.MustCompile(`^(\S+) (\d\d:\d\d) (.+) -> (.+) \((\d+) min\)$`)
m := tripLine.FindStringSubmatch(line)
if m == nil {
// the line doesn't match the pattern
}
// m[0] = the whole line, m[1] = "KRL", m[2] = "07:15", m[3] = "Bogor", ...
The pattern pieces you'll use most:
| Pattern | Meaning |
|---|---|
\d | one digit |
\d+ | one or more digits |
\S+ | one or more characters that aren't spaces |
.+ | one or more characters of any kind |
( ) | a capture group: this part goes into m[1], m[2], ... |
\( | a real parenthesis, not a group |
^ and $ | start and end of the line |
Write patterns in backticks (`) so \d doesn't have to be written \\d. Build the regexp once at package level with MustCompile, not inside a loop.
fmt.Sscanf for small pieces
For very simple shapes, fmt.Sscanf reads values straight into variables:
var hour, minute int
_, err := fmt.Sscanf("07:15", "%d:%d", &hour, &minute) // hour = 7, minute = 15
Sscanf suits short pieces such as a time or a coordinate like 3,4. For a whole long line, a regexp is usually easier to read and tells you clearly when the line doesn't match.
Keep times as minutes
Doing arithmetic with "07:15" is awkward. Turn it into one number, such as minutes after midnight (7*60 + 15 = 435), compute with that, then format it back at the end with fmt.Sprintf("%02d:%02d", h, m). The % operator wraps the time past midnight: (1420 + 545) % 1440 = 525, which is 08:45.
Task
A train timetable is written as <train> <HH:MM> <from> -> <to> (<duration> min). Station names can be more than one word.
- Complete
parseTrip(line string) (Trip, error)withtripLine.FindStringSubmatch. Turn the departure time into minutes after midnight (fmt.Sscanfwith"%d:%d"), and the duration withstrconv.Atoi. Return an error if the line doesn't match the pattern, or if the hour is above 23 or the minute above 59. - Complete
arrival(t Trip) string: the arrival time asHH:MM, wrapping past midnight.