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

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to extract and sort numbers from a string containing numbers and text in Go

1 Answer

0 votes
package main

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

/*
   This program extracts all integer values from a mixed string
   and sorts them using the language's built‑in sorting mechanism.

   It demonstrates:
     - clear separation of concerns using functions
     - efficient number extraction using regular expressions
     - dynamic storage using slices
     - fast sorting with sort.Ints
*/

// ------------------------------------------------------------
// Extract all integer values from a mixed string.
// Uses a regular expression to find digit sequences.
// ------------------------------------------------------------
func extractNumbers(text string) []int {
    // Find all sequences of digits in the string
    re := regexp.MustCompile(`\d+`)
    matches := re.FindAllString(text, -1)

    // Convert each match to an integer
    numbers := make([]int, 0, len(matches))
    for _, m := range matches {
        value, _ := strconv.Atoi(m)
        numbers = append(numbers, value)
    }

    return numbers
}

// ------------------------------------------------------------
// Print all numbers in a space‑separated format.
// ------------------------------------------------------------
func printNumbers(numbers []int) {
    for i, n := range numbers {
        fmt.Print(n)
        if i < len(numbers)-1 {
            fmt.Print(" ")
        }
    }
    fmt.Println()
}

// ------------------------------------------------------------
// Main program
// ------------------------------------------------------------
func main() {
    text := "1000withz7 and3 or 99 give42"

    // extract numbers
    numbers := extractNumbers(text)

    // sort numbers
    sort.Ints(numbers)

    // display result
    fmt.Print("Sorted numbers: ")
    printNumbers(numbers)
}



/*
run:

Sorted numbers: 3 7 42 99 1000

*/

 



answered 12 hours ago by avibootz
...