Regular expression for splitting a URL into its component parts
I'm looking for a way to split a URL into its component parts so I can handle each element. Why? Because the URL is a custom scheme in an iPhone app that I want to handle specifically.
For example, if a user taps a link with the URL myapp://section/?id=123 I want to use the string after the scheme as the indication of which section to jump to in my app开发者_开发百科 and then split the key/value as an indication of which subview to present to the user.
I'm guessing a Regular Expression would do the trick.
Here's an example for the NSURL class and its usage.
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
take a look at the docs for NSURL;
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html
scroll down to
Accessing the Parts of the URL
and see all that NSURL can do for you without a regex...
A regular expression is serious overkill for this. Just split first at ://
, then at /
.
(You could have a loook at using an NSScanner, or as Bill Dudney points out, just use NSURL ;)
精彩评论