2

//The error is here let regex = NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: nil, error: nil)

//The error is:***

cannot find an initializer for type nsregularexpression that accept an argument of type (pattern: string,ption:nil,error:nil)

jose compaq
  • 51
  • 1
  • 5
  • The signature in Swift 2 is: `init(pattern pattern: String, options options: NSRegularExpressionOptions) throws`. – zaph Jul 14 '15 at 13:30

3 Answers3

10

There are 2 changes with regards to the syntax in Swift 2.0: (1) you wrap the call in a try ... catch block instead of supplying an error parameter; and (2) options should be a Set, not a numerical or of the individual options.

In your case the code should look like this:

do {
    let regex = try NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: [])
} catch let error as NSError {
    print(error.localizedDescription)
}

If you know that your pattern always succeeds, you can shorten it like this:

let regex = try! NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: [])

Now if you want to set options to your pattern, you can do this:

let regex = try! NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: [.CaseInsensitive, .AnchorsMatchLines])
Code Different
  • 90,614
  • 16
  • 144
  • 163
2

In Swift2. You need use do try catch for error handling.

do {
    let regex = try NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: NSRegularExpressionOptions.CaseInsensitive)
}catch {
// Handling error
}
Long Pham
  • 7,464
  • 3
  • 29
  • 40
1

NSRegularExpression in Swift 2.0 in xcode 7

 extension String {
     func isEmail() throws -> Bool {
         let regex = try NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$", options: [.CaseInsensitive])

        return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, characters.count)) != nil
}
}

Then when you want to call the method, do it from within a do block and catch the error that comes out.

do {
      try "person@email.com".isEmail()
   } catch {
      print(error)
   }
ViJay Avhad
  • 2,684
  • 22
  • 26