开发者

trim url string. c#

开发者 https://www.devze.com 2023-02-17 13:54 出处:网络
how can i trim a youtube url so it only returns the video id for example http://www.youtube.com/watch?v=VPqTW-9U9nU. how would i return VPqTW-9U9nU. this has to be for several url inputted. I would li

how can i trim a youtube url so it only returns the video id for example http://www.youtube.com/watch?v=VPqTW-9U9nU. how would i return VPqTW-9U9nU. this has to be for several url inputted. I would like to use regex but I do not und开发者_JAVA百科erstand it at all. so if somebody has a solution with regex could you explain it in abit more details :)


Without doing any string manipulation you can use Uri and ParseQueryString

Uri uri = new Uri("http://www.youtube.com/watch?v=VPqTW-9U9nU");
var s = HttpUtility.ParseQueryString(uri.Query).Get("v");


No RegEx needed in this case:

string url = "http://www.youtube.com/watch?v=VPqTW-9U9nU";
string videoId = url.Substring(url.IndexOf("?v=") + 3);


Why not just stick with something simple?

string youTubeUrl = "http://www.youtube.com/watch?v=VPqTW-9U9nU";
string id = youTubeUrl.Replace("http://www.youtube.com/watch?v=", String.Empty);

Regular expressions are handy, but sometimes overkill and can make your code harder to understand when you use them in places you don't need them.


Try something like this:

string url = "http://www.youtube.com/watch?v=VPqTW-9U9nU";
string video_id = url.Substring(0,url.LastIndexOf("=')+1);

The other answers look right, too.


You could also use String.Split():

url.Split(new[] { '=' }, 2)[1]
0

精彩评论

暂无评论...
验证码 换一张
取 消