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

1 Answer

0 votes
import Foundation

/**
 * 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
    let cleaned: String = text.replacingOccurrences(
        of: #"\([^)]*\)"#,
        with: " ",
        options: .regularExpression
    )

    // Collapse multiple spaces into one
    let collapsed: String = cleaned
        .components(separatedBy: .whitespacesAndNewlines)
        .filter { !$0.isEmpty }
        .joined(separator: " ")

    // Final trim of leading/trailing spaces
    return collapsed.trimmingCharacters(in: .whitespacesAndNewlines)
}

let str: String =
    "(An) API (API) (is a) (connection) connects (between) computer programs"

let output: String = removeParenthesesWithContent(str)

print(output)



/*
run:

API connects computer programs

*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz

Related questions

...