Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string of one side letters, one side numbers

Tags:

go

I’m having a mind blank on this one. I am receiving strings of the format.. AB1234 ABC1234 ABC123 AB12 etc etc. Essentially, flight numbers

They could have one or two letters and anything from 1 to 5 numbers. I want to split the string so that I end up with two strings, one with the numbers and one with the letters.

Any ideas? I’ve looked through these but can’t see one that would do the job https://www.dotnetperls.com/split-go

Update:

Just found and will use this unless there’s a better option. Delete all letters / numbers to create the strings needed https://golangcode.com/how-to-remove-all-non-alphanumerical-characters-from-a-string/

like image 487
NickS Avatar asked Jul 10 '18 23:07

NickS


2 Answers

You could take advantage of the fact that Go is a programming language and write a simple Go function. For example,

package main

import (
    "fmt"
)

func parseFlight(s string) (letters, numbers string) {
    var l, n []rune
    for _, r := range s {
        switch {
        case r >= 'A' && r <= 'Z':
            l = append(l, r)
        case r >= 'a' && r <= 'z':
            l = append(l, r)
        case r >= '0' && r <= '9':
            n = append(n, r)
        }
    }
    return string(l), string(n)
}

func main() {
    flights := []string{"AB1234", "ABC1234", "ABC123", "AB12"}
    for _, flight := range flights {
        letters, numbers := parseFlight(flight)
        fmt.Printf("%q: %q %q\n", flight, letters, numbers)
    }
}

Playground: https://play.golang.org/p/pDrsqntAP6E

Output:

"AB1234": "AB" "1234"
"ABC1234": "ABC" "1234"
"ABC123": "ABC" "123"
"AB12": "AB" "12"
like image 195
peterSO Avatar answered Nov 26 '22 01:11

peterSO


It looks like Go's regex syntax does not support lookahead, so you will have to match the two parts and extract them manually, rather than using a split method.

package main

import (
    "regexp"
    "fmt"
)

var reFlightNumbers = regexp.MustCompile("([A-Z]+)([0-9]+)")

func main() {
    matches := reFlightNumbers.FindStringSubmatch("ABC123")
    fmt.Println(matches[1])
    fmt.Println(matches[2])
}
like image 35
merlin2011 Avatar answered Nov 26 '22 02:11

merlin2011