How to remove parentheses and the text inside them from a string in Go

1 Answer

0 votes
package main

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

/**
 * Remove all parentheses and the text inside them.
 *
 * @param text  The input string
 * @return      The cleaned string
 */
func removeParenthesesWithContent(text string) string {
    // Remove parentheses and everything inside them
    re := regexp.MustCompile(`\([^)]*\)`)
    cleaned := re.ReplaceAllString(text, " ")

    // Collapse multiple spaces into one 
    cleaned = strings.Join(strings.Fields(cleaned), " ")

    // Final trim of leading/trailing spaces
    return strings.TrimSpace(cleaned)
}

func main() {
    str := "(An) API (API) (is a) (connection) connects (between) computer programs"
    output := removeParenthesesWithContent(str)

    fmt.Println(output)
}



/*
run:

API connects computer programs

*/

 



answered 1 day ago by avibootz
edited 1 day ago by avibootz

Related questions

...