【问题标题】:How to use regular expressions in Swift 3?如何在 Swift 3 中使用正则表达式?
【发布时间】:2017-04-25 06:35:55
【问题描述】:

本来想关注this tutorial了解Swift中的NSRegularExpression,但是还没有更新到Swift 3。当我使用他们提供的示例打开操场时,我收到了几个错误,其中一个是调用:

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

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

【问题讨论】:

标签: ios regex swift3 nsregularexpression


【解决方案1】:

我相信.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

【讨论】:

    【解决方案2】:

    你可以使用[]:

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

    这也是默认值,所以你可以省略这个参数:

    let regex = try! NSRegularExpression(pattern: pattern)
    

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

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

    【讨论】:

      猜你喜欢
      • 2015-11-30
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      相关资源
      最近更新 更多