add basic parse method

This commit is contained in:
zhiqiang feng
2021-01-04 15:33:14 +08:00
parent 220b1d269d
commit 38e9dc5f03
2 changed files with 100 additions and 29 deletions
+45 -24
View File
@@ -4,26 +4,31 @@ import (
"regexp"
"strconv"
"strings"
"time"
)
type Telegram struct {
Text string
Complete bool
Parsed bool
Fields []string
Sequence int
Type string
Text string
Complete bool
Parsed bool
Fields []string
Sequence int
Type string
FlopValue []string
FlightNumber string
RegisterNumber string
Departure string
DepartureTime time.Time
Destination string
DestinationTime time.Time
DateOfFlight time.Time
ParseErrors []error
}
const (
Start = "ZCZC"
End = "NNNN"
Start = "ZCZC"
End = "NNNN"
TmqRegex = `TMQ(?P<tmq>\d{4})`
FlopRegex = `^\((?P<flop>\w{3})-.*`
TypePLN = "PLN"
)
//Parse
@@ -33,11 +38,17 @@ func Parse(text string) (*Telegram, error) {
telegram.Fields = strings.Split(strings.Replace(text, "\r\n", "\n", -1), "\n")
telegram.Fields = clean(telegram.Fields)
seq := getFields(TmqRegex, telegram.Fields[0])
telegram.Sequence, _ = strconv.Atoi( seq["tmq"])
telegram.Sequence, _ = strconv.Atoi(seq["tmq"])
if isPln(*telegram) {
telegram.Type = TypePLN
} else if t := getFields(FlopRegex, telegram.Fields[3]); t != nil {
telegram.Type = t["flop"]
} else if flopValues := getFields(FlopRegex, telegram.Text); len(flopValues) > 0 {
telegram.Type = flopValues["flop"]
r := regexp.MustCompile(FlopRegex)
data := r.FindString(telegram.Text)
switch telegram.Type {
case TypeArrival:
parseArr(telegram, data)
}
}
return telegram, nil
}
@@ -55,8 +66,7 @@ func clean(fields []string) []string {
return values[:len(values)-1]
}
func getFields(regEx, field string) (fields map[string]string) {
func getFields(regEx string, field string) (fields map[string]string) {
var compRegEx = regexp.MustCompile(regEx)
match := compRegEx.FindStringSubmatch(field)
@@ -70,11 +80,22 @@ func getFields(regEx, field string) (fields map[string]string) {
return
}
func isPln(telegram Telegram) bool {
for _, value := range telegram.Fields {
if strings.HasPrefix(value, TypePLN) {
return true
}
func getFlopValues(s string) []string {
// get rid of ()
s = strings.TrimSpace(s)
s = s[1 : len(s)-1]
return strings.Split(s, "-")
}
func parseFlight(s string) (flightNumber string, registerNumber string) {
if l := strings.Index(s, "/"); l > 0 {
return s[0:l], s[l+1:]
}
return false
return s, ""
}
func getAirportAndTime(s string) (airport string, arrivalTime time.Time) {
fields := getFields(DestinationRegex, s)
arrivalTime, _ = time.Parse("1504", fields["time"])
return fields["dest"], arrivalTime
}