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

时间:2015-12-03 18:33:44

标签: swift swift2

给出以下字符串:

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
    }

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

4 个答案:

答案 0 :(得分:28)

在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的早期版本,请参阅previous revision of this answer

答案 1 :(得分:4)

一个非常基本的方法,并假设你可以保证你可以使用.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"

答案 2 :(得分:1)

对此进行检查

let delimiter = ", "
let newstr = "Hello, playground"
let token = newstr.components(separatedBy: delimiter)
let first = token[0]
let last = token[1]
print("\(first) \(last)")

答案 3 :(得分:-2)

只需使用func substringFromIndex,但按照"Phone:"

的长度增加索引