问题:
我有在其名称中添加了时间戳的文件,如下所示:
"演讲最终project_20141207182834657.pptx">
和
"演讲最终project_201412071864035.pptx">
如何从中删除"_date"部分?
请注意,我无法计算 char,因为有时日期是 15 个字符,有时更多,我需要以某种方式删除以"_20"开头的字符串部分,直到它到达"."(点(或者也许有人有更好的主意。
背景:
我有一个文件的存储,在上传文件之前,我给它一个时间戳,如下所示:
(JavaScript(
function getDate() {
var today = new Date();
var year = today.getFullYear().toString();
var month = (today.getMonth()+1).toString();
var day = today.getDate();
if (day < 10)
day = "0" + day.toString();
else
day = day.toString();
var hours = today.getHours().toString();
var minutes = today.getMinutes().toString();
var seconds = today.getSeconds().toString();
var miliSecond = today.getMilliseconds().toString();
return year+month+day+hours+minutes+seconds+miliSecond;
}
以及我添加到文件名中的此函数返回的内容。
现在我想将文件返回给用户,但没有我添加到文件中的日期戳。
谢谢。
更新
让我给出一个疯狂的场景,不仅在这样的日期之前有下划线"_":
"presentation_final_project_201412071864035.pptx">
我不能信任"_"的索引,因为它可以无处不在。
为了提取文件部分,我将使用 Path 类方法更加独立于操作系统
string input = "presentation final project_20141207182834657.pptx";
string pureFile = Path.GetFileNameWithoutExtension(input);
string ext = Path.GetExtension(input);
int pos = pureFile.LastIndexOf('_');
string newFile = pureFile.Substring(0, pos) + ext;
请注意,要查找下划线,您需要从输入字符串的末尾开始,而不是从头开始以避免误报(在最后一个下划线之前存在下划线(
唯一不确定的一点是日期部分之前或之后存在下划线。如果您可以确定日期之前总是有一个下划线,而在日期之后没有下划线,那么这种方法将完美地工作。
这是相当微不足道的。找到字符的位置并使用Substring()
构建一个新字符串:
string input = "presentation final project_20141207182834657.pptx";
int underscoreIndex = input.LastIndexOf("_");
int dotIndex = input.LastIndexOf(".");
string newFilename = input.Substring(0, underscoreIndex);
newFilename += input.Substring(dotIndex);
在 Ideone.com 上看到它的实际效果。
使用string.LastIndexOf
和string.Remove
来获取文本:
string text = "presentation final project_20141207182834657.pptx";
int indexOfUnderscore = text.LastIndexOf('_'); // find the position of _
int indexOfPeriod = text.LastIndexOf('.', indexOfUnderscore); // find the position of .
// find remove the text between _ and .
string newText = text.Remove(indexOfUnderscore, indexOfPeriod - indexOfUnderscore);
字符串 r = "演示文稿最终project_2011207182834657.pptx";
string part1 = r.Substring(0, r.IndexOf(@"_"));
string part2 = r.Substring(r.IndexOf(@"."), 5);
Console.WriteLine(part1);
Console.WriteLine(part2);
Console.WriteLine(part1 + part2);
string oldpath = "presentation_final_project_201412071864035.pptx";
string date = oldpath.Split('_').LastOrDefault().Split('.').FirstOrDefault();
string newpath = oldpath.Replace("_" + date, "");
这是一个正则表达式解决方案
string file = "presentation final project_201412071864035.pptx";
var result = Regex.Replace(file, @"(.*)(_[d]{15,})(.*)$", "$1$3");