How do I get the last part of this filepath?

2019-05-21 11:47发布

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?

4条回答
forever°为你锁心
2楼-- · 2019-05-21 11:58

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;
    }
}
查看更多
beautiful°
3楼-- · 2019-05-21 12:00
    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());
    }
查看更多
在下西门庆
4楼-- · 2019-05-21 12:06

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[]{'\\'});
查看更多
唯我独甜
5楼-- · 2019-05-21 12:19

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.

查看更多
登录 后发表回答