Skip to content

Commit

Permalink
Switch to a regexp to extract train IDs.
Browse files Browse the repository at this point in the history
  • Loading branch information
bamnet committed Sep 2, 2024
1 parent 9d031c1 commit 7e11169
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
2 changes: 1 addition & 1 deletion testdata/getVehicleData.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
<LATITUDE>41.374876</LATITUDE>
</TRAIN>
<TRAIN>
<ID>6659</ID>
<ID>6659.</ID>
<TRAIN_LINE>Morris &amp; Essex Line</TRAIN_LINE>
<DIRECTION>Westbound</DIRECTION>
<ICS_TRACK_CKT>EE-41UP</ICS_TRACK_CKT>
Expand Down
14 changes: 9 additions & 5 deletions vehicle_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/xml"
"errors"
"regexp"
"strconv"
"strings"
"time"
Expand All @@ -17,6 +18,8 @@ const (

var (
ErrTrainNotFound = errors.New("train not found")

trainIDRe = regexp.MustCompile(`(\d+)`)
)

// A Train summarizes the latest information about a train.
Expand Down Expand Up @@ -193,12 +196,13 @@ func (c *Client) VehicleData(ctx context.Context) ([]Train, error) {

trains := make([]Train, len(data.Trains))
for i, d := range data.Trains {
// Remove any "a" (amtrak) suffix from the ID.
d.ID = strings.TrimSuffix(d.ID, "a")

// Remove any "." prefixes from the ID.
// Use a Regex to extract the numbers from the ID.
// Some trains have an "a" (amtrak suffix). Others
// randomly have leading or trailing ".".
//
// https://github.com/bamnet/njtapi/issues/7
d.ID = strings.TrimPrefix(d.ID, ".")
idM := trainIDRe.FindStringSubmatch(d.ID)
d.ID = idM[1]

id, err := strconv.Atoi(d.ID)
if err != nil {
Expand Down

0 comments on commit 7e11169

Please sign in to comment.