Search code examples
delphifiremonkeydelphi-10.2-tokyo

Finding and copy a text next to a string


i want to search a text written just next to a string or text in ini and copy it or directly read from TINI into TEdit.

i.e.

[Section]
Indent=AA1:BB2ac:CC35sda:DDWord`

i want to show the text written next to CC,which is 35sda, in TEdit.

I Tried copy function but not the pos and posex() function. Thank You.


Solution

  • This is simply a matter of basic string parsing, such as with Pos(), PosEx(), and Copy(), eg:

    Ini := TMemIniFile.Create('file.ini');
    try
      S := Ini.ReadString('Section', 'Indent', '');
      StartIdx := Pos(':CC', S) + 3;
      EndIdx := PosEx(':', S, StartIdx);
      Edit1.Text := Copy(S, StartIdx, EndIdx - StartIdx);
    finally
      Ini.Free;
    end;
    

    Or, using TStringHelper:

    Ini := TMemIniFile.Create('file.ini');
    try
      S := Ini.ReadString('Section', 'Indent', '');
      StartIdx := S.IndexOf(':CC') + 3;
      EndIdx := S.IndexOf(':', StartIdx);
      Edit1.Text := S.Substring(StartIdx, EndIdx - StartIdx);
    finally
      Ini.Free;
    end;
    

    Or, you could use a TStringList to help you parse, eg:

    Ini := TMemIniFile.Create('file.ini');
    try
      SL := TStringList.Create;
      try
        SL.Delimiter := ':';
        SL.StrictDelimiter := True;
        SL.DelimitedText := Ini.ReadString('Section', 'Indent', '');
        Edit1.Text := Copy(SL[2], 3, MaxInt);
        // or:
        // Edit1.Text := SL[2].Substring(2);
      finally
        SL.Free;
      end;
    finally
      Ini.Free;
    end;