简体   繁体   English

替换动态字符串中的部分文本

[英]Replace part of text in a dynamic string

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 ) 并将其替换为**../** ,并保留路径的第二部分( media/reports/Darth_Vader_Report.pdf

If I knew the length or size of it, I could use the Replace or Substring . 如果知道长度或大小,可以使用ReplaceSubstring 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. 在对StriplingWarrior提出问题之后,我意识到我可以做得更好。

The objective is to replace everything behind /media . 目的是替换/media后面的所有内容。 The “media” directory is static, and will always be the decisive part of the path. “ media”目录是静态的,并且将始终是路径的决定性部分。

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. 我没有检查它,但我认为它应该可以解决问题。

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! 祝好运!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM