Search code examples
swiftstringswiftuisubstringtrim

Trimming Substrings from String Swift/SwiftUI


Let's say I have the following strings:

"Chest Stretch (left)"
"Chest Stretch (right)"

How can I use SwiftUI to output only:

"Chest Stretch"

I thought this may be a possible duplicate of swift - substring from string.

However, I am seeking a way to do this inside var body: some View within an if conditional expression.


Solution

  • A possible way is Regular Expression

    let string = "Chest Stretch (left)"
    let trimmedString = string.replacingOccurrences(of: "\\s\\([^)]+\\)", with: "", options: .regularExpression)
    

    The found pattern will be replaced with an empty string.

    The pattern is:

    • One whitespace character \\s
    • An opening parenthesis \\(
    • One or more characters which are not a closing parentheses [^)]+
    • and a closing parenthesis \\)

    Or simpler if the delimiter character is always the opening parenthesis

    let trimmedString = String(string.prefix(while: {$0 != "("}).dropLast())
    

    Or

    let trimmedString = string.components(separatedBy: " (").first!