URL中的C#正则表达式信息

本文关键字:信息 正则表达式 中的 URL | 更新日期: 2023-09-27 18:30:04

我有以下URL:

http://vk.com/video#/video219171498_166164529
http://vk.com/video?gid=21095903#/video-21095903_165699050
http://vk.com/video#/video219171498_166164529

我需要从这些字符串中获取信息"video219171498_166164529"。也许有一个代码可以取"视频"和后面的19个符号。对不起我的英语

URL中的C#正则表达式信息

您实际上可以通过仅使用Split()来获取值。

string _str = "http://vk.com/video#/video219171498_166164529";
var _arr = _str.Split("/");
string _value = _arr[_arr.length - 1];

我不确定你的问题的标题是否重要,但为了扩展其他人的有效答案,如果你确实需要(?)使用正则表达式,你可以获得与其他人相同的结果。C#使用System.Text.RegularExpression,因此可以执行类似操作来提取"视频…"字符串。

string pattern = "(video['w-]+)";
string url = "http://blahblah/video-12341237293";
Match match = Regex.Match(url, pattern);
// Here you can test Match to check there was a match in the first place
// This will help with multiple urls that are dynamic rather than static like the above example
string result = match.Groups[1].Value;

在上面的例子中,结果将等于url中的匹配字符串。使用Match首先检查是否匹配意味着您可以将其放入循环中,并遍历List/Array等,而无需知道url值,也无需更改特定情况下的模式。

不管怎样,你可能不需要Regex,但如果你需要的话,我希望以上的帮助。

为了改进491243的答案,我会这样做:

 string _str = "http://vk.com/video#/video219171498_166164529";
 string _arr = _str.Split("/").Last();
string _str = "http://vk.com/video#/video219171498_166164529";
var index = _str.LastIndexOf("/");
var value = _str.SubString(index + 1);

请确保添加错误处理