2

让我们以这个字符串为例:

D:/firstdir/Another One/and 2/bla bla bla/media/reports/Darth_Vader_Report.pdf

我想切断路径的第一部分:

D:/firstdir/Another One/and 2/bla bla bla

并将其替换为**../**, 并保留路径的第二部分 ( media/reports/Darth_Vader_Report.pdf)

如果我知道它的长度或大小,我可以使用Replaceor Substring。但是由于字符串的第一部分是动态的,我该怎么做呢?


更新

在 StriplingWarrior 提出问题后,我意识到我可以更好地解释。

目标是替换后面的一切/media。“媒体”目录是静态的,并且始终是路径的决定性部分。

4

3 回答 3

3

你可以这样做:

string fullPath = "D:/firstdir/Another One/and 2/bla bla bla/media/reports/Darth_Vader_Report.pdf"
int index = fullPath.IndexOf("/media/");
string relativePath = "../" + fullPath.Substring(index);

我还没有检查它,但我认为它应该可以解决问题。

于 2010-10-27T18:53:43.797 回答
3

使用正则表达式:

Regex r = new Regex("(?<part1>/media.*)");
var result = r.Match(@"D:/firstdir/Another One/and 2/bla bla bla/media/reports/Darth_Vader_Report.pdf");
if (result.Success)
{
    string value = "../" + result.Groups["part1"].Value.ToString();
    Console.WriteLine(value);
}

祝你好运!

于 2010-10-27T18:54:48.680 回答
0

我会写下面的正则表达式模式,

String relativePath = String.Empty;
Match m = Regex.Match("Path", "/media.*$");
if (m.Success)
{
relativePath = string.Format("../{0}", m.Groups[0].Value);
}
于 2010-10-27T19:00:54.020 回答