问题
//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