如何在Swift 3中使用正则表达式?

时间:2016-12-09 17:55:48

标签: ios regex swift3 nsregularexpression

我想关注this tutorial以了解NSRegularExpression中的Swift,但尚未更新为Swift 3。当我用他们提供的示例打开游乐场时,我得到了几个错误,其中一个是调用:

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

我已经看到,现在初始化程序抛出异常,所以我更改了调用,但.allZeros似乎不再存在。我没有找到任何与Swift 3相同的教程或示例,有人可以告诉我现在应该用哪个选项替换.allZeros选项吗?

2 个答案:

答案 0 :(得分:7)

我认为在没有应用其他选项时会使用.allZeros

因此,使用Swift 3,您可以传递一个空的选项列表或省略options参数,因为它默认为无选项:

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

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

请注意,在Swift 3中,您不再使用error参数。它现在throws

答案 1 :(得分:5)

您可以使用[]

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

也是默认值,因此您可以省略此参数:

let regex = try! NSRegularExpression(pattern: pattern)

找到这个的最简单方法是命令+单击跳转到方法定义:

public init(pattern: String, options: NSRegularExpression.Options = []) throws