Nona
Nona

Reputation: 5472

How to split a string containing non-numeric characters into a string array in Go?

How would I split and filter a string containing non-numeric characters into a string array containing only numeric characters?

E.g.,

str := "035a 444$ bb" 
//split str into s
s := []string{"0", "3", "5", "4", "4", "4"} 

Upvotes: 2

Views: 2531

Answers (2)

Shiva Kishore
Shiva Kishore

Reputation: 1701

This should work.

func getNumericChars(s string) []string {
    var result []string
    // iterating through each character in string
    for _, c := range strings.Split(s, "") {
        // if character can be converted to number append it to result 
        if _, e := strconv.Atoi(c); e == nil {
            result = append(result, c)
        }
    }
    return result
}

call s := getNumericChars("035a 444$ bb").
s will be [0 3 5 4 4 4]

Upvotes: 0

Michael Hampton
Michael Hampton

Reputation: 10000

You're trying to do two separate things here, so you need to first separate them in your mind:

First, you are trying to remove all non-numeric characters.

Second, you are trying to split all remaining characters into a slice containing single characters.

There is no built in function to remove non-numeric characters from a string, but you can write a regular expression match and replace to do this:

str := "035a 444$ bb"

reg, err := regexp.Compile("[^0-9]+")
if err != nil {
    panic(err)
}

numericStr := reg.ReplaceAllString(str, "")

The regex matches any character that is not in 0-9 inclusive. Then regexp.ReaplceAllString() replaces those characters with nothing.

This causes numericStr to contain the string

"035444"

After that, you can use strings.Split() to get the slice you want.

s := strings.Split(numericStr, "")

The documentation tells us that:

If sep is empty, Split splits after each UTF-8 sequence.

So s becomes:

[]string{"0", "3", "5", "4", "4", "4"}

Upvotes: 3

Related Questions