Swift: how to get everything after a specific character set

Given the following line:

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

How can I extract everything that comes after "Phone:"

So in this case I want

 phone = 123.456.7891 

I tried this:

  if let range = snippet.rangeOfString("Phone:") { let phone = snippet.substringToIndex(range.startIndex) print(phone) // prints 1111 West Main Street Beverly Hills, CA 90210 } 

But it prints everything before, I need everything AFTER.

+7
swift swift2
source share
3 answers

In Swift 4, use the upperBound and index operators and the open range:

 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" } 

Or consider trimming spaces:

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

By the way, if you are trying to grab both at the same time, a regex can do this:

 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)!] } 

For previous versions of Swift, see the previous version of this answer .

+9
source share

for the easiest way and assuming you can guarantee the format of the string you could use .components(separatedBy: "Phone:") so that everything is before index 0 and after index 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
source share

Just use func substringFromIndex , but increase the index by the length of "Phone:"

-one
source share

All Articles