Search code examples
stringdelphimasking

Subtract a mask from a string in Delphi 10.3


I collect resource dll file names into TStringList by a given mask. It works fine to that point. After that I want to collect the language codes contained by the file names. Is there any built-in function or a well formed regexp to get the right string section depending on the mask?

Example 1:

Mask : resources_%s.dll

One of the collected file names : resources_en.dll

Language code : en

Example 2:

Mask : %s_resources.dll

One of the collected file names : eng_resources.dll

Language code : eng

Example 3:

Mask : res-%s.dll

One of the collected file names : res-en.dll

Language code : en


Solution

  • In general, this problem is mathematically impossible to solve.

    For instance, consider the mask alpha_%s_beta_%s_gamma and the output alpha_cat_beta_beta_dog_gamma.

    It is possible that the first value is cat and the second is beta_dog, but it could also be the case that the first value is cat_beta and the second is dog. So additional information must be given.

    If, for instance, you know that the mask always contains exactly one (1) instance of %s, then the problem is very easy to solve. For instance (omitting all error checking):

    function GetValueFromMask(const AMask, AText: string): string;
    var
      p: Integer;
    begin
      p := Pos('%s', AMask);
      Result := Copy(AText, p, 2 + AText.Length - AMask.Length);
    end;
    

    Of course, you would never use that code in production. You would add error checking, making sure you handle AText not matching AMask, AMask containing zero or >1 %s, etc.

    But you get the idea.