How do I get the last part of this filepath?

流过昼夜 提交于 2019-12-06 09:19:26
Jim Skerritt

Here's a solution that uses regular expressions, assuming the format you're looking for always contains \yyyy\MM\dd\HH\mm.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(ExtractPath(@"C:\Temp\X\2012\08\27\18\35\wy32dm1q.qyt"));
        Console.WriteLine(ExtractPath(@"D:\Temp\X\Y\2012\08\27\18\36\tx84uwvr.puq"));
    }

    static string ExtractPath(string fullPath)
    {
        string regexconvention = String.Format(@"\d{{4}}\u{0:X4}(\d{{2}}\u{0:X4}){{4}}\w{{8}}.\w{{3}}", Convert.ToInt32(Path.DirectorySeparatorChar, CultureInfo.InvariantCulture));

        return Regex.Match(fullPath, regexconvention).Value;
    }
}
    static void Main(string[] args)
    {
        Console.WriteLine(GetLastParts(@"D:\Temp\X\Y\2012\08\27\18\36\tx84uwvr.puq", @"\", 6));
        Console.ReadLine();
    }

    static string GetLastParts(string text, string separator, int count)
    {
        string[] parts = text.Split(new string[] { separator }, StringSplitOptions.None);
        return string.Join(separator, parts.Skip(parts.Count() - count).Take(count).ToArray());
    }

A c# solution would be

string str = @"C:\Temp\X\2012\08\27\18\35\wy32dm1q.qyt";
string[] arr=str.Substring(str.IndexOf("2012")).Split(new char[]{'\\'});

I don't think there's anything wrong w/ your current approach. It's likely the best for the job.

public string GetFilepath(int nth, string needle, string haystack) {
    int lastindex = haystack.Length;

    for (int i=nth; i>=0; i--)
        lastindex = haystack.LastIndexOf(needle, lastindex-1);

    return haystack.Substring(lastindex);
}

I'd keep it simple (KISS). Easier to debug/maintain and probably twice as fast as regex variant.

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