如何在Xcode 7中的Swift 2.0中使用NSRegularExpression [英] How to use NSRegularExpression in Swift 2.0 in xcode 7
问题描述
//错误在这里let regex = NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: nil, error: nil)
//错误是:***
找不到nsregularexpression类型的初始化程序,该初始化程序接受 类型的参数(模式:字符串,ption:无,错误:无)
cannot find an initializer for type nsregularexpression that accept an argument of type (pattern: string,ption:nil,error:nil)
推荐答案
在Swift 2.0中,语法有2处更改:(1)将调用包装在try ... catch
块中,而不是提供error
范围;和(2)options
应该是Set
,而不是各个选项的数字or
.
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])
这篇关于如何在Xcode 7中的Swift 2.0中使用NSRegularExpression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!