Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,919 questions

51,852 answers

573 users

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
...