How to print all log lines containing a specific date from a text block in Pascal

1 Answer

0 votes
program LogFinder;

{$mode objfpc}{$H+} // Use Object Pascal mode and Ansistrings (dynamic strings)

uses
  Classes, SysUtils, StrUtils;

// Type definition for a dynamic array of strings 
type
  TStringArray = array of string;

{ Find all log lines with a given date }
function FindAllLogsByDate(const Logs: string; const TargetDate: string): TStringArray;
var
  Lines: TStringArray;
  Matches: TStringArray;
  Line: string;
  MatchCount: Integer;
begin
  MatchCount := 0;
  SetLength(Matches, 0);

  { Split the big string by newline characters, mimicking std::getline loop.
    We handle both \n (Linux/macOS) and \r\n (Windows) by splitting on \n 
    and trimming if necessary. }
  Lines := SplitString(Logs, #10);

  for Line in Lines do
  begin
    { Pos returns > 0 if the substring is found, equivalent to != std::string::npos }
    if Pos(TargetDate, Line) > 0 then
    begin
      Inc(MatchCount);
      SetLength(Matches, MatchCount);
      // Remove any leftover carriage returns (#13) from Windows line endings
      Matches[MatchCount - 1] := TrimRight(Line); 
    end;
  end;

  Result := Matches;
end;

var
  Logs: string;
  Results: TStringArray;
  R: string;

begin
  // Multi-line string concatenation using regular string literals
  Logs := 
    '01/12/2023 - Log entry one.' + #10 +
    '17/03/2021 - Log entry two.' + #10 +
    '29/07/2019 - Log entry three.' + #10 +
    '05/11/2024 - Log entry four.' + #10 +
    '22/08/2020 - Log entry five.' + #10 +
    '14/02/2018 - Log entry six.' + #10 +
    '30/09/2022 - Log entry seven.' + #10 +
    '11/06/2017 - Log entry eight.' + #10 +
    '03/04/2025 - Log entry nine.' + #10 +
    '05/11/2024 - Log entry ten.';

  Results := FindAllLogsByDate(Logs, '05/11/2024');

  // For-in loop to iterate through the results (requires FPC 2.4.2+)
  for R in Results do
  begin
    WriteLn(R);
  end;
end.




(* 
run:

05/11/2024 - Log entry four.
05/11/2024 - Log entry ten.

*)

 



answered 10 hours ago by avibootz

Related questions

...