MaryLitv21
MaryLitv21

Reputation: 449

Regex for numeric inside brackets in Swift

In my app, I have a textField for URL input, and I need to check if the user enters any numeric with brackets inside of it. If there is such numeric with brackets inside my textField, I need to remove it. For example, if the user inputs "stackoverflow.com(1)", I need to immediately change it to "stackoverflow.com". I can't find any way to check if there is number inside brackets. What I've tried:

   if urlField.text!.contains("(\([0-9]))") {
            let numberInBrackets = NSCharacterSet(charactersIn: "(\([0-9]))")
            let urlWithoutBrackets = urlField.text!.trimmingCharacters(in: numberInBrackets as CharacterSet)
            DispatchQueue.main.async {
                self.urlField.text = urlWithoutBrackets
            }
        }

The problem is in regex (("(\([0-9]))")), it doesn't seem to work.

Any help is appreciated!

Upvotes: 1

Views: 248

Answers (1)

Ryszard Czech
Ryszard Czech

Reputation: 18611

Use

if let text = self.urlField.text {
    self.urlField.text = text.replacingOccurrences(of: #"\([0-9]+\)"#, with: "", options: .regularExpression) 
}

EXPLANATION

--------------------------------------------------------------------------------
  \(                       '('
--------------------------------------------------------------------------------
  [0-9]+                   any character of: '0' to '9' (1 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  \)                       ')'

Upvotes: 1

Related Questions