How to extract all digits from a string in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "unicode"
    "strings"
)

/*
    extractDigits
    -------------
    Walks through the input string and collects only characters
    that are classified as digits by the Unicode standard.

    Using unicode.IsDigit ensures correct behavior for all
    Unicode digit characters, not just ASCII '0'–'9'.

    A strings.Builder is used for efficient string construction.
*/
func extractDigits(s string) string {
    var b strings.Builder

    // Iterate over runes to correctly handle Unicode input
    for _, r := range s {
        // Check whether the rune is a digit
        if unicode.IsDigit(r) {
            b.WriteRune(r)
        }
    }

    // Return the collected digits
    return b.String()
}

func main() {
    // Example input string
    str := "5 ruby8go 9001 c c++ go 173python"

    // Extract digits
    digits := extractDigits(str)

    // Display results
    fmt.Println("Original:", str)
    fmt.Println("Digits:  ", digits)
}


/*
run:

Original: 5 ruby8go 9001 c c++ go 173python
Digits:   589001173

*/

 



answered Sep 16 by avibootz
...