Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to get everything after a certain set of characters

Tags:

swift

swift2

Given the following string:

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've 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 this prints everything BEFORE, I need everything AFTER.

like image 317
user1625155 Avatar asked Dec 03 '15 18:12

user1625155


3 Answers

In Swift 4, use upperBound and subscript operators and 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 the whitespace:

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're trying to grab both at the same time, a regular expression can do that:

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

For prior versions of Swift, see previous revision of this answer.

like image 118
Rob Avatar answered Sep 26 '22 15:09

Rob


for a very basic way and assuming you can guarantee the format of the string you could use .components(separatedBy: "Phone: ") so anything before will be at 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"
like image 24
RyanTCB Avatar answered Sep 26 '22 15:09

RyanTCB


Check it this

let delimiter = ", "
let newstr = "Hello, playground"
let token = newstr.components(separatedBy: delimiter)
let first = token[0]
let last = token[1]
print("\(first) \(last)")
like image 42
Sreekanth G Avatar answered Sep 25 '22 15:09

Sreekanth G