How do I get the last part of this filepath?

扶醉桌前 提交于 2019-12-08 02:49:39

问题


I have a filepath that follows the following pattern:

Some\File\Path\Base\yyyy\MM\dd\HH\mm\Random8.3

I want to extract everything from 2012 and beyond, but the problem is that while the right side is standard the base directory can be different for each record.

Here are two examples:

  1. C:\Temp\X\2012\08\27\18\35\wy32dm1q.qyt
    Returns: 2012\08\27\18\35\wy32dm1q.qyt

  2. D:\Temp\X\Y\2012\08\27\18\36\tx84uwvr.puq
    Returns: 2012\08\27\18\36\tx84uwvr.puq

Right now I'm grabbing the LastIndexOf(Path.DirectorySeparatorChar) N number of times to get the index of the string right before 2012, then getting the substring from that index on. But, I have a feeling that maybe there is a better way?


回答1:


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



回答2:


    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());
    }



回答3:


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[]{'\\'});



回答4:


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.



来源:https://stackoverflow.com/questions/12199600/how-do-i-get-the-last-part-of-this-filepath

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