C# 替换动态字符串中的部分文本
让我们以这个字符串为例:C# 替换动态字符串中的部分文本,c#,asp.net,regex,string-math,C#,Asp.net,Regex,String Math,让我们以这个字符串为例: D:/firstdir/other One/和2/bla bla bla bla/media/reports/Darth_Vader_Report.pdf 我想切割路径的第一部分: D:/firstdir/另一个/和2/bla-bla-bla-bla 并将其替换为**../**,并保留路径的第二部分 (media/reports/Darth\u Vader\u Report.pdf) 如果我知道它的长度或大小,我可以使用替换或子字符串。但是,既然字符串的第一部分是动态的
D:/firstdir/other One/和2/bla bla bla bla/media/reports/Darth_Vader_Report.pdf
我想切割路径的第一部分:
D:/firstdir/另一个/和2/bla-bla-bla-bla
并将其替换为**../**
,并保留路径的第二部分
(media/reports/Darth\u Vader\u Report.pdf
)
如果我知道它的长度或大小,我可以使用替换
或子字符串
。但是,既然字符串的第一部分是动态的,我该怎么做呢
更新 在回答了这个问题之后,我意识到我本可以解释得更好
目标是替换
/media
后面的所有内容。“媒体”目录是静态的,并且始终是路径的决定性部分。您可以这样做:
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);
我还没有检查它,但我认为它应该可以做到这一点。使用正则表达式:
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);
}
Regex r=newregex((?/media.*);
var result=r.Match(@“D:/firstdir/另一个/和2/bla-bla-bla/media/reports/Darth_Vader_Report.pdf”);
如果(结果、成功)
{
字符串值=“../”+result.Groups[“part1”].value.ToString();
控制台写入线(值);
}
祝你好运 我将编写以下正则表达式模式
String relativePath = String.Empty;
Match m = Regex.Match("Path", "/media.*$");
if (m.Success)
{
relativePath = string.Format("../{0}", m.Groups[0].Value);
}
您如何确定要替换的路径的哪一部分?解释逻辑:你第一次看到“/media/”这个词时一切都好吗?我已经更新了我的问题,希望这能有所帮助。:)通常,我会选择
Regex
解决方案,但这次我会选择一个简单的.IndexOf(…)
+1这很容易出现一些问题,比如你要寻找的“媒体”之前的“中间”一词。您可能需要使用LastIndexOf。这在很大程度上取决于你能依赖多少字符串;到目前为止,我们只知道“媒体”。@Jason:它并不完美。但我认为它与“中间”一词不匹配,因为我检查了“/media”的索引,即包括斜杠。我还将更新我的答案,以检查“/media/”,这将使它更加安全。由于您的解决方案对非常有效,我决定给您一个+1。但在一天结束时,我决定使用Homam解决方案。无论如何谢谢你:)太好了!成功了!!:)非常感谢你。