I have a string below.
String s = "2014-12-19_16-09-19_test.10_A.txt";
what is the best way to extract the '2014-12-19_16-09-19' from the string rather then use String.Split()?
I have tried with regex but only extract '2014-12-19'.
(\d+)[-.\/](\d+)[-.\/](\d+)
Use this regex:
Regex regex = new Regex(@"\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}");
Assumption: The string to be searched for is in the format "2014-12-19_16-09-19" only. If the separators are different, or if number of digits is variable, the regex has to be updated accordingly.
Alternatively, if the position of the underscores is always fixed, you could avoid regexes altogether. You can split by underscore and then join back the first and second elements of the split array, like so:
var v = s.Split('_');
Console.WriteLine(string.Join("_", new string[] {v[0],v[1]}));
Demo
I would use the following method:
const string format = "yyyy-MM-dd_HH-mm-ss";
String s = "2014-12-19_16-09-19_test.10_A.txt";
var dateTimeSubstring = s.Substring(0, format.Length);
var dt = DateTime.ParseExact(dateTimeSubstring, format, CultureInfo.CurrentCulture);
Console.WriteLine(dt);
With this code, you will get a 'dt' variable of type DateTime, with all functionality, like dt.Year, dt.Month, etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With