ios String.range 在 Swift 3.0 中的使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39126003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:59:21  来源:igfitidea点击:

Usage of String.range in Swift 3.0

iosswift3

提问by H. Cliff

let us = "http://example.com"
let range = us.rangeOfString("(?<=://)[^.]+(?=.com)", options:.RegularExpressionSearch)
if range != nil {
    let found = us.substringWithRange(range!)
    print("found: \(found)") // found: example
}

This code extracts substringbetween backslashes and dot com in Swift 2. I searched Internet and I found that rangeOfStringchanged to range().

这段代码substring在 Swift 2 中的反斜杠和 dot com 之间提取。我搜索了互联网,发现它rangeOfString变成了range().

But still I could not make the code work in Swift 3.0. Could you help me ?

但是我仍然无法使代码在 Swift 3.0 中工作。你可以帮帮我吗 ?

edit : I'm using swift 3 07-25 build.

编辑:我正在使用 swift 3 07-25 build。

回答by Nirav D

In swift 3.0rangeOfStringsyntax changed like this.

在 swift 3.0 中,rangeOfString语法变成了这样。

let us = "http://example.com"
let range = us.range(of:"(?<=://)[^.]+(?=.com)", options:.regularExpression)
if range != nil {
     let found = us.substring(with: range!)
     print("found: \(found)") // found: example
}

回答by pedrouan

In latest swift 3.0 using Xcode 8 Beta 6 (latest updates to SDK):

在最新的 swift 3.0 中,使用 Xcode 8 Beta 6(SDK 的最新更新):

let us = "http://example.com"
let range = us.range(of: "(?<=://)[^.]+(?=.com)", options: .regularExpression)
if range != nil {
    let found = us.substring(with: range!)
    print("found: \(found)") // found: example
}