A regular expression for breaking a URL into its constituent parts

I am looking for a way to split a URL into its constituent parts so that I can process each element. What for? Because the url is a custom schema in the iPhone app that I want to work specifically with.

For example, if the user removes the link with the URL myapp: // section /? id = 123, I want to use the line after the diagram as an indication of which section to go into my application, and then split the key / value as an indication of which subview to present to the user.

I assume that regex will do the trick.

+3
source share
3 answers

Here is an example of the NSURL class and its use.

NSURL *url = [NSURL URLWithString:@"foo://name.com:8080/12345;param?foo=1&baa=2#fragment"];

NSLog(@"scheme: %@", [url scheme]); 
NSLog(@"host: %@", [url host]); 
NSLog(@"port: %@", [url port]);     
NSLog(@"path: %@", [url path]);     
NSLog(@"path components: %@", [url pathComponents]);        
NSLog(@"parameterString: %@", [url parameterString]);   
NSLog(@"query: %@", [url query]);       
NSLog(@"fragment: %@", [url fragment]);

output:

scheme: foo
host: name.com
port: 8080
path: /12345
path components: (
    "/",
    12345
)
parameterString: param
query: foo=1&baa=2
fragment: fragment
+6
source

Regular expression is a serious overkill for this. First divide first by ://, then by /.

(You may have loook when using NSScanner , or, as Bill Dudney points out, just use NSURL;)

0
source

All Articles