Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strings - get characters before a digit

Tags:

go

I have some strings such E2 9NZ, N29DZ, EW29DZ . I need to extract the chars before the first digit, given the above example : E, N, EW. Am I supposed to use regex ? The strings package looks really nice but just doesn't seem to handle this case (extract everything before a specific type).

Edit:

To clarify the "question" I'm wondering what method is more idiomatic to go and perhaps likely to provide better performance.

like image 411
themihai Avatar asked Oct 14 '25 07:10

themihai


1 Answers

For example,

package main

import (
    "fmt"
    "unicode"
)

func DigitPrefix(s string) string {
    for i, r := range s {
        if unicode.IsDigit(r) {
            return s[:i]
        }
    }
    return s
}

func main() {
    fmt.Println(DigitPrefix("E2 9NZ"))
    fmt.Println(DigitPrefix("N29DZ"))
    fmt.Println(DigitPrefix("EW29DZ"))
    fmt.Println(DigitPrefix("WXYZ"))
}

Output:

E
N
EW
WXYZ

If there is no digit, example "WXYZ", and you don't want anything returned, change return s to return "".

like image 186
peterSO Avatar answered Oct 17 '25 23:10

peterSO