我有一个由文件名组成的字符串。我想从字符串中提取日期部分。 文件名是这样的: -
CA48_SOLANO_Scan_May_2014-05-22_NONE.xls
NJ08_Gloucester_Scan_March_2014-03-26_ None.xlsm
OH06_AUGLAIZE_SCAN_MARCH_2014-03-12_NONE.xls
OH06_AUGLAIZE_SCAN_MARCH_2014-03-09_NONE.xls
在这里,我想从每个字符串中提取2014-05-22
,2014-03-26
,2014-03-12
,2014-03-0
9。我知道这可能来自Regex但不能生成正则表达式这符合我的要求。
答案 0 :(得分:2)
使用string.Split代替正则表达式似乎很简单
var arr = str.Split('_');
string date = arr[arr.Length-2];
修改您可以使用\d{4}-\d{2}-\d{2}
\d
代表数字,{num
}代表长度-
。
Match match = Regex.Match(strDate, "(\\d{4}-\\d{2}-\\d{2})", RegexOptions.IgnoreCase);
if (match.Success)
Console.WriteLine(match.Groups[1].Value);
答案 1 :(得分:1)
答案 2 :(得分:0)
答案 3 :(得分:0)
我认为你不需要RegEx。使用RegEx,您可以从字符串中决定是否是电子邮件,日期等...
我认为最好编写一个函数来从文件名中获取日期。像这样。
public static DateTime getDateFromFileName(string fileName)
{
string[] temp = fileName.Split('-');
int year = Convert.ToInt32(temp[0].Remove(0, temp[0].Length - 4));
int month = Convert.ToInt32(temp[1]);
int day = Convert.ToInt32(temp[2].Remove(2));
DateTime date = new DateTime(year, month, day);
return date;
}
答案 4 :(得分:0)
您可以尝试以下代码片段。
string example = "<myfilename.txt>_19680615.csv";
string time = Regex.Replace(example, @"(.*?)(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})\.csv", "${year}-${month}-${day}");
Console.WriteLine(time);
还包括在代码中使用System.Text.RegularExpressions命名空间。