if I have a string, lets say
var test string = "The number is 12345"
How can I trim everything from the string except for the digits?
Thanks in advance!
My first (not necessarily best) thought would be to use
regular expressions:
package main
import "regexp"
import "fmt"
func main() {
re := regexp.MustCompile( "[^0-9]" )
fmt.Printf( re.ReplaceAllString( "hello 12 34 five", "" ) )
}
Chris
[Typed into goplay for testing ...]
--
Chris "allusive" Dollin
> func TrimToNum(r int) bool {
> if n := r - '0'; n >= 0 && n <= 9 {
> return false
> }
> return true
> }
Why not
return r < '0' || '9' < r
?
Chris
--
Chris "allusive" Dollin
> Your code doesn't "trim everything from the string except for the
> digits." It replaces, it doesn't trim.
It's not clear (to me) whether the OP was limiting themselves
to "trim from the ends". That's why the example I gave explicitly
had a space embedded in the digit sequence, so that if that's
not what they wanted they could have said so.
There is also strings.Map.