![](/img/trans.png)
[英]How to convert NSURLConnecion statement to Xcode 7 (swift 2.0)?
[英]How to use NSRegularExpression in Swift 2.0 in xcode 7
//錯誤在這里let regex = NSRegularExpression(pattern: "(<img.*?src=\\")(.*?)(\\".*?>)", options: nil, error: nil)
//錯誤是:***
找不到接受類型參數的類型nsregularexpression的初始值設定項(pattern:string,ption:nil,error:nil)
關於Swift 2.0中的語法有兩處變化:(1)你將調用包裝在try ... catch
塊中而不是提供error
參數; (2) options
應為Set
,而不是數字or
個別選項。
在您的情況下,代碼應如下所示:
do {
let regex = try NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: [])
} catch let error as NSError {
print(error.localizedDescription)
}
如果您知道您的模式總是成功,您可以像這樣縮短它:
let regex = try! NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: [])
現在,如果要為模式設置選項,可以執行以下操作:
let regex = try! NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: [.CaseInsensitive, .AnchorsMatchLines])
在Swift2中。 你需要使用do
try
catch
的錯誤處理。
do {
let regex = try NSRegularExpression(pattern: "(<img.*?src=\")(.*?)(\".*?>)", options: NSRegularExpressionOptions.CaseInsensitive)
}catch {
// Handling error
}
xcode 7中的Swift 2.0中的NSRegularExpression
extension String {
func isEmail() throws -> Bool {
let regex = try NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$", options: [.CaseInsensitive])
return regex.firstMatchInString(self, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, characters.count)) != nil
}
}
然后,當您想要調用該方法時,請從do塊中執行此操作並捕獲出現的錯誤。
do {
try "person@email.com".isEmail()
} catch {
print(error)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.