Multi Line Memo in delphi

3.2k views Asked by At

I am confused to get a particular word started line in Memo in Delphi 7

I have something like this

Memo1.lines.text:= *Some execution process*;

and the result in Memo1 is

I have something to do 
I have never gone there 
We are playing Tenis
You are so sweet

I am going there

Now How can I get only the line started with We instead of whole bunch of lines

like in the above Memo lines

We are playing Tenis

3

There are 3 answers

12
Ken White On

If you know you always want a specific line (like the third in your sample), access it directly. Lines, like TStringList, is zero-based, so subtract one:

YourLine := Memo1.Lines[2];

If you only have part of the text at the beginning of the line, you can iterate through each line and use StrUtils.StartsText:

var
  i: Integer;
  FoundAt: Integer;
begin
  FoundAt := -1;
  for i := 0 to Memo1.Lines.Count - 1 do
  begin
    if StrUtils.StartsText('We', Memo1.Lines[i]) then
      FoundAt := i;
  end;
  if FoundAt <> -1 then
    YourText := Memo1.Lines[FoundAt];
end;

In Delphi 7, use AnsiStartsText instead (also found in the StrUtils unit).

3
Arioch 'The On
j := FirstLineStarting( Memo1.Lines, 'we' );
if j >= 0 then 
   ShowMessage( Memo1.Lines[j] ); 


.....


function FirstLineStarting( const Text: TStrings; const Pattern: string; const WithCase: Boolean = false): integer;
var i: integer;
    check: function (const ASubText, AText: string): Boolean;
begin
  Result := -1; // not found

  if WithCase
     then check := StartsStr
     else check := StartsText;

  for i := 0 to Text.Count - 1 do
     if check( Pattern, Text[i] ) then begin
        Result := i;
        break;
     end; 
end;
0
RepeatUntil On

Uses StrUtils

Function sExtractBetweenTagsB(Const s, LastTag, FirstTag: string): string;
var
  pLast,pFirst,pNextFirst : Integer;
begin
  pFirst := Pos(FirstTag,s);
  pLast := Pos(LastTag,s);
  while (pLast > 0) and (pFirst > 0) do begin
    if (pFirst > pLast) then // Find next LastTag
      pLast := PosEx(LastTag,s,pLast+Length(LastTag))
    else
    begin
      pNextFirst := PosEx(FirstTag,s,pFirst+Length(FirstTag));
      if (pNextFirst = 0) or (pNextFirst > pLast) then begin
        Result := Trim(Copy(s,pFirst,pLast-pFirst+Length(LastTag)));
        Exit;
      end
      else
        pFirst := pNextFirst;
    end;
  end;
  Result := '';
end;

Usage like this

procedure TForm24.btn1Click(Sender: TObject);
begin
  ShowMessage(sExtractBetweenTagsB(Memo1.Text,sLineBreak,'We'));
  //or
  ShowMessage(sExtractBetweenTagsB(Memo1.Text,'Tenis','We'));
end;

Output: We are playing Tenis