2

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"} 

2 Answers 2

3

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"}
Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.