给出以下字符串:
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 }
但这会打印出所有东西,我需要一切.
在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的早期版本,请参阅此答案的先前版本.
以一种非常基本的方式,并假设您可以保证可以使用的字符串格式,.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"