How to use NSRegularExpression in Swift 2.0 in xcode 7

你离开我真会死。 提交于 2019-12-22 18:21:10

问题


//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)


回答1:


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])



回答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
}



回答3:


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


来源:https://stackoverflow.com/questions/31406706/how-to-use-nsregularexpression-in-swift-2-0-in-xcode-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!