Search code examples
swiftswift3

Remove substring between parentheses


I need a function in Swift 3 which will remove content in a string between parentheses. E.g for a string like "THIS IS AN EXAMPLE (TO REMOVE)" should return "THIS IS AN EXAMPLE"

I'm trying to use removeSubrange method but I'm stuck.


Solution

  • Most simple Shortest solution is regular expression:

    let string = "This () is a test string (with parentheses)"
    let trimmedString = string.replacingOccurrences(of: #"\s?\([\w\s]*\)"#, with: "", options: .regularExpression)
    

    The pattern searches for:

    • An optional whitespace character \s?.
    • An opening parenthesis \(.
    • Zero or more word or whitespace characters [\w\s]*.
    • A closing parenthesis \).

    Alternative pattern is #"\s?\([^)]*\)"# which represents:

    • An optional whitespace character \s?.
    • An opening parenthesis \(.
    • Zero or more characters anything but a closing parenthesis [^)]*.
    • A closing parenthesis \).