从字符串中提取信息

时间:2017-05-24 10:14:50

标签: ios regex swift

我有一个URL形式的字符串。字符串看起来像

http://www.somezwebsite.com/en/someString/xx-38944672

我对网址的最后一部分/xx-38944672感兴趣。我需要在最后xx/之间提取-,这可能是一个或多个字符。我还需要在此示例中提取数字38944672。这个数字也可能有不同的长度。

我想我可以通过确定最后一个索引或最后一个索引 - 以及字符串中最后一个字符的索引来实现这一点,然后继续子字符串。有更清洁的方法吗?

3 个答案:

答案 0 :(得分:1)

这是你需要的那个:

/\w+(?=-)/g

DEMO

答案 1 :(得分:0)

关键字URL意味着解决方案的一部分

代码采用URL的最后一个路径组件,并通过-字符将值分成两部分:

let url = URL(string:"http://www.somezwebsite.com/en/someString/xx-38944672")!
let components = url.lastPathComponent.components(separatedBy: "-")
if components.count == 2 {
    let firstPart = components[0]
    let secondPart = components[1]
    print(firstPart, secondPart)
}

答案 2 :(得分:0)

可以这样做:

let urlString = "http://www.somezwebsite.com/en/someString/xx-38944672"
        let str = urlString.components(separatedBy: "/").last
        let firstSring = str?.components(separatedBy: "-").first
        let secondString = str?.components(separatedBy: "-").last