[英]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.