Home > front end >  Swift regex format to remove string contains brackets in iOS
Swift regex format to remove string contains brackets in iOS

Time:02-21

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: "(")

CodePudding user response:

Use replacingOccurrences(…)

let result = str.replacingOccurrences(of: #"\(.*\)"#, 
                                      with: "", 
                     options: .regularExpression)
    .trimmingCharacters(in: .whitespaces))

CodePudding user response:

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)
}
  • Related