Reputation: 2105
How to get all characters after the last '/' (slash) from url string?
I receive a json string from my URL scheme when making webview request for certain site. For example:
app://ga/ecommerce/%7B%22product%22:%22playstation4%22...}]
I would like to grab the substring after the last '/'(slash).
How can I achieve it? May I know what is the format of Regex?
Avoid to use
NSRange lastDotRange = [sURL rangeOfString:@"/" options:NSBackwardsSearch];
because I might have escaped '/' in my json.
Thank you.
Upvotes: 13
Views: 13068
Reputation: 11646
some Swift samples, to get the "query" and last part of an url. Note if You have a string, you have to create an URL, so the URL class can manage correctly the parts. (String has no capabilities to perform so).
sample:
let s = "https://example.com/search?q=Display+iphone"
let url = URL(string: s)
let lastOnUrl = url?.lastPathComponent
let query = url?.query
print("lastOnUrl:", lastOnUrl!)
print("query: ", query!)
You will get:
lastOnUrl: search
query: q=Display+iPhone
Upvotes: 0
Reputation: 599
For Swift 3 try this.
let fileName = "your/file/name/here"
let fileArray = fileName?.components(separatedBy: "/")
let finalFileName = fileArray?.last
Output : "Here"
Upvotes: 32
Reputation: 2105
Well it seems like using Regex is quite expensive inside shouldStartLoadWithRequest delegate especially if you're having hybrid app which has plenty webviews. Some of my websites in webview might have more than one request, some are running at the background. It's painful if the webview triggers regex codes everytime when webview loads the request.
And also, I have escaped '/' in my last component params (json string), it might cause the lastComponent breaks after the escaped '/' character.
Therefore I stick to the codes filtering by using if-else statements and also compare strings with components of URL For example
request.URL.absoluteString
request.URL.host
request.URL.fragment
and also found out that @Nitin Gohel is useful.
Upvotes: 0
Reputation: 471
try this:
NSURL *url = [NSURL URLWithString:@"app://ga/ecommerce/%7B%22product%22:%22playstation4%22..."];
NSString *last = [url lastPathComponent];
Upvotes: 7
Reputation: 49720
You may split string in array and get last object from array like following:
NSString *myString = @"app://ga/ecommerce/product:playstation4";
NSArray* spliteArray = [myString componentsSeparatedByString: @"/"];
NSString* lastString = [spliteArray lastObject];
Upvotes: 2
Reputation: 3057
The regex you need is something like this:
((\/){1}([a-z\-]*))$
Which will match 1 slash, with all lowercase letters and hyphens. You can add more characters in there, like A-Z for capital letters (etc), and the '$' places matches it from the end of the string,
Upvotes: 0
Reputation: 52538
Create an NSURL and use the NSURL methods, like lastPathComponent, or parameterString. These methods are presumably written by someone who knows how to handle URLs.
Upvotes: 2