import Foundation
func cleanString(_ text: String) -> String {
// Step 1: Remove parentheses and their content (non-greedy)
let withoutParen = text.replacingOccurrences(
of: "\\([^)]*\\)",
with: "",
options: .regularExpression
)
// Step 2: Collapse multiple spaces into one
let collapsedSpaces = withoutParen.replacingOccurrences(
of: "\\s+",
with: " ",
options: .regularExpression
)
// Step 3: Trim leading/trailing spaces
return collapsedSpaces.trimmingCharacters(in: .whitespacesAndNewlines)
}
let original = "Hello (remove this) from the future (and this too)"
let cleaned = cleanString(original)
print("Original: \(original)")
print("Cleaned : \(cleaned)")
/*
run:
Original: Hello (remove this) from the future (and this too)
Cleaned : Hello from the future
*/