Reputation: 15282
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:
C:\Temp\X\2012\08\27\18\35\wy32dm1q.qyt
Returns: 2012\08\27\18\35\wy32dm1q.qyt
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?
Upvotes: 2
Views: 2341
Reputation: 3216
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.
Upvotes: 0
Reputation: 4596
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;
}
}
Upvotes: 3
Reputation:
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());
}
Upvotes: 4
Reputation: 73
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[]{'\\'});
Upvotes: 0