开发者

Replace part of text in a dynamic string

开发者 https://www.devze.com 2023-01-22 20:07 出处:网络
Let’s take this string has an example: D:/firstdir/Another One/and 2/bla bla bla/media/reports/Darth_Vader_Report.pdf

Let’s take this string has an example:

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

I want to cut the first part of the path:

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

And replace it with **../**, and keep the second part of the path (media/reports/Darth_Vader_Report.pdf)

If I knew the length o开发者_如何学运维r size of it, I could use the Replace or Substring. But since the first part of the string is dynamic, how can I do this?


Update

After StriplingWarrior question, I realized that I could have explained better.

The objective is to replace everything behind /media. The “media” directory is static, and will always be the decisive part of the path.


Use Regular Expressions:

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

Good luck!


You could do something like this:

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

I haven't checked it, but I think it should do the trick.


I would write the following regex pattern,

String relativePath = String.Empty;
Match m = Regex.Match("Path", "/media.*$");
if (m.Success)
{
relativePath = string.Format("../{0}", m.Groups[0].Value);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消