PHP-like string parsing

I am writing a mini console and I am trying to figure out how to extract things from a link. For example, in PHP, this is a query variable like this:

http://somelink.com/somephp.php?variable1=10&variable2=20

PHP then calculates the URL parameters and assigns them to a variable.

How would I parse something like this in Swift?

So, given the line I want to take: variable1 = 10 and variable2 = 20, etc., is there an easy way to do this? I tried to walk, but did not know what I was looking for.

I have a really terrible hacker way to do this, but it cannot expand.

+4
source share
1 answer

You need to NSURLComponents:

import Foundation

let urlStr = "http://somelink.com/somephp.php?variable1=10&variable2=20"
let components = NSURLComponents(string: urlStr)

components?.queryItems?.first?.name   // Optional("variable1")
components?.queryItems?.first?.value  // Optional("10")

It may be useful subscriptfor you to add an operator for the query elements:

extension NSURLComponents {
    subscript(queryItemName: String) -> String? {
        // of course, if you do this a lot, 
        // cache it in a dictionary instead
        for item in self.queryItems ?? [] {
            if item.name == queryItemName {
                return item.value
            }
        }
        return nil
    }
}

if let components = NSURLComponents(string: urlStr) {
    components["variable1"] ?? "No value"
}
+7
source

Source: https://habr.com/ru/post/1589314/


All Articles