简体   繁体   中英

How can I remove a last part of a string with an unknown int?

So, I'm making a file transfer program from one PC in my house to the other. The client can look through the server's files and take what it wants. (Makes it very easy for moving projects/documents/music). This is an example of what a string of a file looks like:

New Text Document.txt : "(FILE)-(" + f.Length + " Bytes)"

My problem is removing : "(FILE)-(" + f.Length + " Bytes)". How can I remove JUST that part from the string? Where the f.Length is unknown... Thanks!

Just as an alternative to the regex answers, one option is to use LastIndexOf to find the last occurence of a known part of the string (eg (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);

I hope I've got what you want

string contents = "some text (FILE)-(5435 Bytes)  another text";

string result = Regex.Replace(contents, @"\(FILE\)-\(\d+ Bytes\)", "");

Console.WriteLine (result);

Prints:

some text   another text

Solution to remove everything after .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);

prints some text .txt

var match = Regex.Match(pattern: @"\((.*)\)-\(\d+ Bytes\)$", input: name);
if(match.Success)
{
    string fileName = match.Groups[1].Value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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