Reputation:
So I have this string which I have to trim and manipulate a little with it. My string example:
string test = "studentName_123.pdf";
Now, what I want to do is somehow extract only the _123
part and at the end I need to have studentName.pdf
What I have tried:
string test_extracted = test.Substring(0, test.LastIndexOf("_") )+".pdf";
This also works but the thing is that I don't want to add the ".pdf" suffix at the end of the string manually because I can have strings that are not pdf, for ex. studentName.docx
, studentName.png
.
So basically I just want the "_123" part removed but still keep the remain part after that.
Upvotes: 2
Views: 166
Reputation: 424
This could be solved with a regular expression like this
(\w*)_.*(\.\w*)
where the first capture group (\w*)
matches everything before the underscore and the second group (\.\w*)
matches the file extensions.
Lastly we just have to concat the groups without the stuff inbetween like so:
string test = "studentName_123.pdf";
var regex = Regex.Match(test, @"(\w*)_.*(\.\w*)");
string newString = regex.Groups[1].Value + regex.Groups[2].Value;
Upvotes: 0
Reputation: 31
Since you know what value you will always be replacing in your strings, "_123", to base on your example, just utilize the replace method and replace it with nothing since the method expects two arguments;
string test_extracted = test.replace('_123', '');
Upvotes: 0
Reputation: 469
I think this might help you:
string test = "studentName_123.pdf";
string test_extracted = test.Substring(0, test.LastIndexOf("_") )+ test.Substring(test.LastIndexOf("."),test.Length - test.LastIndexOf(".") );
Using Remove(int startIndex, int count):
string test = "studentName_123.pdf";
string test_extracted = test.Remove(test.LastIndexOf("_"), test.LastIndexOf(".") - test.LastIndexOf("_"));
Upvotes: 1
Reputation: 359
Sounds like you mean something like this?
string extension = Path.GetExtension(test);
string pdfName = Path.GetFileNameWithoutExtension(test).Split('_')[0];
string fullName = pdfName + extension;
Upvotes: 0