How to extract the number from the end of a string in Go

2 Answers

0 votes
package main

import (
	"fmt"
	"regexp"
	"strconv"
)

func extractLastNumber(str string) int {
	re := regexp.MustCompile(`\d+`)

	matches := re.FindAllString(str, -1)
	lastNumber, _ := strconv.Atoi(matches[len(matches) - 1])

	return lastNumber
}

func main() {
	str := "go 84 programming2309"

	n := extractLastNumber(str)

	fmt.Println(n)
}



/*
run:

2309

*/

 



answered Aug 17, 2024 by avibootz
0 votes
package main

import (
	"fmt"
	"strconv"
	"unicode"
)

func extractLastNumber(str string) int {
	i := len(str)

	for i > 0 && unicode.IsDigit(rune(str[i - 1])) {
		i--
	}

	n, _ := strconv.Atoi(str[i:])

	return n
}

func main() {
	str := "go 13 programming8901"

	n := extractLastNumber(str)

	fmt.Print(n)
}


/*
run:

8901

*/

 



answered Aug 17, 2024 by avibootz
...