Is there some way to test if a date is contained in a string?

Viewed 126

Delphi 10.4

I need to check if the last 8 or 10 characters of a string fit a date mask. I would like to do this using only pure Delphi code. Any ideas?

Examples of data:

Docket 05/04/98

Docket 12/11/2021

Something like

if DocumentName <> '' then
begin
  //* Test for date as part of the document name and remove it if it is.
  if IsDateMask(RStr(DocumentName,8),'00|/00|/00',-1) then
    DocumentName := Copy(DocumentName,1,length(DocumentName)-9)

  else
    if IsDateMask(RStr(DocumentName,10),'00|/00|/0000',-1) then
      DocumentName := Copy(DocumentName,1,length(DocumentName)-11);

  ...
end;
1 Answers

You can simply use TRegEx to extract date value :

uses
  System.SysUtils,
  RegularExpressions,
  Classes;

var
  List: TStringList;
  s: string;
  Value: string;
begin
  List := TStringList.Create;

  try
    List.Add('Docket 05/04/98');
    List.Add('Docket none');
    List.Add('Docket 12/11/2021');
    List.Add('Docket 01/2021');

    for s in List do
    begin
      Value := TRegEx.Match(s, '\d{2}\D\d{2}\D(\d{4}|\d{2})').Value;
      Writeln(Format('StringValue=%s', [s]));
      Writeln(Format('DateValue=%s', [Value]));
      Writeln('------------------------------------------');
    end;

    Readln;
  finally
    FreeAndNil(List);
  end;
end.

Output value will be :

StringValue=Docket 05/04/98
DateValue=05/04/98
------------------------------------------
StringValue=Docket none
DateValue=
------------------------------------------
StringValue=Docket 12/11/2021
DateValue=12/11/2021
------------------------------------------
StringValue=Docket 01/2021
DateValue=
------------------------------------------
Related