Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading