当前位置:  开发笔记 > IOS > 正文

Swift:如何在一组特定字符后获取所有内容

如何解决《Swift:如何在一组特定字符后获取所有内容》经验,为你挑选了2个好方法。

给出以下字符串:

var snippet = "1111 West Main Street Beverly Hills, CA 90210 Phone: 123.456.7891"

如何提取"电话:"之后的所有内容

所以在这种情况下我想要

phone = 123.456.7891

我试过这个:

    if let range = snippet.rangeOfString("Phone:") {

        let phone = snippet.substringToIndex(range.startIndex)
        print(phone) // prints 1111 West Main Street Beverly Hills, CA 90210
    }

但这会打印出所有东西,我需要一切.



1> Rob..:

在Swift 4中,使用upperBound和下标运算符和开放范围:

let snippet = "1111 West Main Street Beverly Hills, CA 90210 Phone: 123.456.7891"

if let range = snippet.range(of: "Phone: ") {
    let phone = snippet[range.upperBound...]
    print(phone) // prints "123.456.7891"
}

或者考虑修剪空白:

if let range = snippet.range(of: "Phone:") {
    let phone = snippet[range.upperBound...].trimmingCharacters(in: .whitespaces)
    print(phone) // prints "123.456.7891"
}

顺便说一句,如果你想同时抓住两者,正则表达式可以做到这一点:

let snippet = "1111 West Main Street Beverly Hills, CA 90210 Phone: 123.456.7891"
let regex = try! NSRegularExpression(pattern: "^(.*?)\\s*Phone:\\s*(.*)$", options: .caseInsensitive)
if let match = regex.firstMatch(in: snippet, range: NSRange(snippet.startIndex ..< snippet.endIndex, in: snippet)) {
    let address = snippet[Range(match.range(at: 1), in: snippet)!]
    let phone = snippet[Range(match.range(at: 2), in: snippet)!]
}

对于Swift的早期版本,请参阅此答案的先前版本.



2> RyanTCB..:

以一种非常基本的方式,并假设您可以保证可以使用的字符串格式,.components(separatedBy: "Phone:")因此之前的任何内容都将位于索引0处,而位于索引1之后

var snippet = "1111 West Main Street Beverly Hills, CA 90210 Phone: 123.456.7891"
let phoneNumber = snippet.components(separatedBy: "Phone: ")[1]
print(phoneNumber)
//prints everything that appears after "Phone:" in your snippet string
//"123.456.7891"

推荐阅读
女女的家_747
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有