如何在Swift中的句子中的特定关键字之前获取单词?

时间:2019-04-05 08:04:25

标签: swift

  

Aipda Karel Sasuit Tubun No.106B,RT.2 / RW.1,Ps。巴鲁,卡拉瓦奇,哥打   印度尼西亚万丹15112坦格朗”

我有一个这样的字符串地址,我想获取邮政编码15112,该邮政编码始终位于“印度尼西亚”之前

我是一个初学者,很抱歉,这很简单,因为我在Stackoverflow中找不到它

3 个答案:

答案 0 :(得分:0)

对不起,我认为这是一个冗长的方法,但这应该可行:

let address = "Aipda Karel Sasuit Tubun No.106B, RT.2/RW.1, Ps. Baru, Karawaci, Kota Tangerang, Banten 15112, Indonesia"
let keyword = "Indonesia"

let components: [String] = address.split(separator: " ").map({ String($0).replacingOccurrences(of: ",", with: "") })
var postCode = components.first ?? ""

for comp in components {
    if comp == keyword {
        break
    }
    postCode = comp
}

print(postCode)

答案 1 :(得分:0)

let address = "Aipda Karel Sasuit Tubun No.106B, RT.2/RW.1, Ps. Baru, Karawaci, Kota Tangerang, Banten 15112, Indonesia"

func postcode(from address: String, for area: String) -> String? {
    let array = address.replacingOccurrences(of: ",", with: "").components(separatedBy: " ")
    if let index = array.lastIndex(where: { $0.contains(area) }) {
        return array[index - 1]
    }
    return nil
}

postcode(from: address, for: "Indonesia")

答案 2 :(得分:0)

您可以使用正则表达式:

let str = "Aipda Karel Sasuit Tubun No.106B, RT.2/RW.1, Ps. Baru, Karawaci, Kota Tangerang, Banten 15112, Indonesia"
let range = NSRange(location: 0, length: str.utf16.count)
let regex = try! NSRegularExpression(pattern: "[0-9]+(?=, Indonesia)")

if let match = regex.firstMatch(in: str, range: range) {
    let subStr = String(str[Range(match.range, in: str)!])
    print(subStr) //15112
}