从Swift中的String中提取某些文本

Net*_*Cod 0 regex uitextfield ios swift

我希望在Swift 2.x中执行此操作:假设我在文本字段中输入文本.- 'Apple iPhone http://www.apple.com '

我现在正在更新带有标签的UIButton - Apple iPhone.当点击按钮启动' http://www.apple.com时,我想要IBAction .

我可以设置它,但我遇到麻烦的部分是 - 我如何从文本字段解析'Apple iPhone'和' http://www.apple.com '并将它们分开以便我可以更新UIButton标签一些文本并使用URL启动Safari?更具体地说,我希望能够检测"http://"之后的任何"文本",并始终使用文本来更新标签,并使用http来启动带有URL的浏览器.谢谢回答.

Min*_*ina 6

如下所述,这个问题有一个简单的解决方案

var x = "Apple iPhone http://www.apple.com"

@IBAction func click(_ sender: UIButton) {
    let url = x.substring(from: x.range(of: "http")!.lowerBound)
    UIApplication.shared.openURL(NSURL(string: url)! as URL)
}
Run Code Online (Sandbox Code Playgroud)

但是这个解决方案和所有给定的解决方案都存在问题,如果你有这样的字符串:var x = "Apple iPhone http://www.apple.com wwdc"你无法得到正确的结果.通用解决方案可以是这样的:

@IBAction func click(_ sender: UIButton) {
    var text = "Apple iPhone http://www.apple.com wwwdc"

    let startIndex = text.range(of: "http")?.lowerBound
    var startString = text.substring(from: startIndex!)
    let endIndex = startString.range(of: " ")!.lowerBound
    var url = startString.substring(to: endIndex)

    UIApplication.shared.openURL(NSURL(string: url)! as URL)

}
Run Code Online (Sandbox Code Playgroud)

它会正确提取网址.