Вопрос

Good morning and happy end of the world to you all, I have a date related issue which is non apocalyptic related

I'm trying locate a date within a text document. The line with the date on it has text in front and behind it however when I use the TryParseExact I only seem to be able to find the date if its at the beginning of the line of text.

How would I go about altering the below code to search for a date which is located around 20 characters in on the line of text?

DateTime d = DateTime.Now;
            var format1 = "dd/MM/yyyy";
            var fileDates1 = System.IO.File.ReadAllLines(z)
                            .Where(l => l.Length >= format1.Length
                                        && DateTime.TryParseExact(l.Substring(0, format1.Length)
Это было полезно?

Решение 2

Your code is indeed checking only at the beginning of the line.

You can combine a regular expression to find things that look like dates, and then proper parsing to check that the "date" is valid:

DateTime d;
var format1 = "dd/MM/yyyy";
Regex r = new Regex("[0-3][0-9]/[0-1][0-9]/[0-9]{4}");
var linesWithDates = System.IO.File.ReadAllLines(z)
    .Where(l => r.Matches(l).Cast<Match>()
         .Any(DateTime.TryParseExact(m.Value, format1, ...)));

Другие советы

You can use regular expression to find your date in text;

String text = File.ReadAllLines(z);
String pattern = @"\d{2}/\d{2}/\d{4}";
String dateString = Regex.Match(text, pattern).Value;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top