How to remove text between parentheses in a string using Go

1 Answer

0 votes
package main

import (
    "fmt"
    "regexp"
    "strings"
)

func cleanString(text string) string {
    // Step 1: Remove parentheses and their content (non-greedy)
    reParen := regexp.MustCompile(`\([^)]*\)`)
    cleaned := reParen.ReplaceAllString(text, "")

    // Step 2: Collapse multiple spaces into one
    reSpaces := regexp.MustCompile(`\s+`)
    cleaned = reSpaces.ReplaceAllString(cleaned, " ")

    // Step 3: Trim leading/trailing spaces
    cleaned = strings.TrimSpace(cleaned)

    return cleaned
}

func main() {
    original := "Hello (remove this) from the future (and this too)"
    result := cleanString(original)

    fmt.Println("Original:", original)
    fmt.Println("Cleaned :", result)
}


/*
run:

Original: Hello (remove this) from the future (and this too)
Cleaned : Hello from the future

*/

 



answered Dec 18, 2025 by avibootz

Related questions

...