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
*/