Get all characters after the last '/' (slash) from url string

為{幸葍}努か 提交于 2020-04-29 11:58:21

问题


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.


回答1:


For Swift 3 try this.

let fileName = "your/file/name/here"
let fileArray = fileName?.components(separatedBy: "/")
let finalFileName = fileArray?.last

Output : "Here"




回答2:


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.




回答3:


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];



回答4:


try this:

    NSURL *url = [NSURL URLWithString:@"app://ga/ecommerce/%7B%22product%22:%22playstation4%22..."];
    NSString *last = [url lastPathComponent];



回答5:


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,




回答6:


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.



来源:https://stackoverflow.com/questions/36175805/get-all-characters-after-the-last-slash-from-url-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!