AppsDev
AppsDev

Reputation: 12509

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?

Upvotes: 6

Views: 5751

Answers (2)

shallowThought
shallowThought

Reputation: 19602

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

Upvotes: 5

rmaddy
rmaddy

Reputation: 318924

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.

Upvotes: 7

Related Questions