swift2 Swift:如何获得某个字符集后的所有内容

yqhsw0fo  于 2022-11-06  发布在  Swift
关注(0)|答案(4)|浏览(208)

给定以下字符串:

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

如何提取“Phone:“之后的所有内容
在这种情况下我想

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
    }

但这打印之前的一切,我需要之后的一切。

9w11ddsr

9w11ddsr1#

在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..., 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

jum4pzuy

jum4pzuy2#

对于一个非常基本的方法,假设您可以保证字符串的格式,您可以使用.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"
ufj5ltwl

ufj5ltwl3#

检查一下这个

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

lsmepo6l4#

只需使用func substringFromIndex,但将索引增加"Phone:"的长度

相关问题