[英]How can I remove a last part of a string with an unknown int?
因此,我正在制作一台从我家里一台PC到另一台PC的文件传输程序。 客户端可以浏览服务器的文件并获取所需文件。 (使移动项目/文档/音乐非常容易)。 这是文件字符串的示例:
New Text Document.txt : "(FILE)-(" + f.Length + " Bytes)"
我的问题是删除:“(FILE)-(” + f.Length +“字节)”。 如何从字符串中删除该部分? f.Length未知的地方...谢谢!
作为正则表达式答案的替代方法,一种选择是使用LastIndexOf查找字符串的已知部分(例如(FILE)
)的最后一次出现。
var oldString = "ThisIsAString (FILE)-(1234 Bytes";
int indexToRemoveTo = oldString.LastIndexOf("(FILE)");
// Get all the characters from the start of the string to "(FILE)"
var newString = oldString.Substring(0, indexToRemoveTo);
我希望我有你想要的
string contents = "some text (FILE)-(5435 Bytes) another text";
string result = Regex.Replace(contents, @"\(FILE\)-\(\d+ Bytes\)", "");
Console.WriteLine (result);
印刷品:
some text another text
解决方案.txt
后删除所有内容
string contents = "some text .txt (FILE)-(5435 Bytes) another text";
string lastSegment = ".txt";
var result = contents.Substring(0, contents.IndexOf(lastSegment) + lastSegment.Length);
Console.WriteLine (result);
打印some text .txt
var match = Regex.Match(pattern: @"\((.*)\)-\(\d+ Bytes\)$", input: name);
if(match.Success)
{
string fileName = match.Groups[1].Value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.