如何在字符串的特定子字符串后获取字符串?

时间:2012-11-09 16:50:29

标签: c# .net string

  

可能重复:
  How do I extract PART of a specific string from a huge chunk of ugly strings?

字符串:

https://company.zendesk.com/api/v2/tickets/33126.json

我需要号码33126。

提取此数字的最佳方式是什么?

2 个答案:

答案 0 :(得分:6)

由于这是路径/网址,请使用Path.GetFileNameWithoutExtension

string name = Path.GetFileNameWithoutExtension(path);

我更喜欢Path,但是如果您想使用Uri类,您也可以使用它:

Uri uri = new Uri("https://company.zendesk.com/api/v2/tickets/33126.json");
string lastSegment = uri.Segments.Last();
string name = lastSegment.Substring(0, lastSegment.IndexOf('.'));

答案 1 :(得分:0)

这看起来像是正则表达式的工作。

        Regex regex = new Regex(@"https://company.zendesk.com/api/v2/tickets/(\d+).json");

        Match match = regex.Match("https://company.zendesk.com/api/v2/tickets/33126.json");

        foreach(Group group in match.Groups)
        {
            Console.WriteLine(group.Value);
        }
相关问题