我如何获得这个文件路径的最后一部分? [英] How do I get the last part of this filepath?

查看:319
本文介绍了我如何获得这个文件路径的最后一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有遵循以下图案的文件路径:

I have a filepath that follows the following pattern:

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

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

我想从2012年及以后提取的一切,但问题是,而右侧是标准的基本目录可以是不同的。每个记录

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.

下面是两个例子:


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

    返回: 2012\08\27 \18\35\wy32dm1q.qyt

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

返回: 2012\08\27\18\36\tx84uwvr。 PUQ

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

现在,我抓住了 LastIndexOf(次Path.DirectorySeparatorChar) N多得到的字符串指数在2012年以前吧,然后让从该指数的子字符串。但是,我有一种感觉,也许有更好的办法?

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?

推荐答案

下面是一个使用正则表达式的解决方案,假设格式你要找总是包含\yyyy\MM\dd\HH\mm。

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

这篇关于我如何获得这个文件路径的最后一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆