所以,我正在制作一个从我家中的一台 PC 到另一台 PC 的文件传输程序。客户端可以查看服务器的文件并获取它想要的内容。(使移动项目/文档/音乐变得非常容易)。这是文件字符串的示例:
New Text Document.txt : "(FILE)-(" + f.Length + " Bytes)"
我的问题是删除:“(文件)-(”+ 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;
}