Reputation: 51
//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)
Upvotes: 2
Views: 3470
Reputation: 2700
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 "[email protected]".isEmail()
} catch {
print(error)
}
Upvotes: 1
Reputation: 93151
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])
Upvotes: 10
Reputation: 7582
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
}
Upvotes: 2