skip to Main Content

Need to remove part of the string based on brackets.

For ex:

let str = "My Account (_1234)"

I wanted to remove inside brackets (_1234) and the result should be string My Account

Expected Output:

My Account

How can we achieve this with regex format or else using swift default class,need support on this.

Tried with separatedBy but it splits string into array but that is not the expected output.

str.components(separatedBy: "(")

2

Answers


  1. Use replacingOccurrences(…)

    let result = str.replacingOccurrences(of: #"(.*)"#, 
                                          with: "", 
                         options: .regularExpression)
        .trimmingCharacters(in: .whitespaces))
    
    Login or Signup to reply.
  2. Regex ist not necessary. Just get the range of ( and extract the substring up to the lower bound of the range

    let str = "My Account (_1234)"
    if let range = str.range(of: " (") {
        let account = String(str[..<range.lowerBound])
        print(account)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search