Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regular expressions in Swift 3?

I wanted to follow this tutorial to learn about NSRegularExpression in Swift, but it has not been updated to Swift 3. When I open the playground with the examples they provide, I get several errors being one of them the call:

let regex = NSRegularExpression(pattern: pattern, options: .allZeros, error: nil)

I've seen that now that initializer throws an exception so I changed the call, but that .allZeros does not seem to exist anymore. I don't find any tutorial or example with an equivalent of that in Swift 3, could somebody tell me what option should now replace such .allZeros option?

like image 961
AppsDev Avatar asked Dec 09 '16 17:12

AppsDev


2 Answers

I believe .allZeros was to be used when no other options applied.

So with Swift 3, you can pass an empty list of options or leave out the options parameter since it defaults to no options:

do {
    let regex = try NSRegularExpression(pattern: pattern, options: [])
} catch {
}

or

do {
    let regex = try NSRegularExpression(pattern: pattern)
} catch {
}

Note that in Swift 3 you don't use the error parameter any more. It now throws.

like image 139
rmaddy Avatar answered Sep 19 '22 22:09

rmaddy


You can use []:

let regex = try! NSRegularExpression(pattern: pattern, options: [])

which is also the default value, so you can omit this argument:

let regex = try! NSRegularExpression(pattern: pattern)

The easiest way to find this out is to command+click jump to the methods definition:

public init(pattern: String, options: NSRegularExpression.Options = []) throws
like image 38
shallowThought Avatar answered Sep 19 '22 22:09

shallowThought