TMatchCollectionCount (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of TMatchCollection and TGroupCollection. This example assumes that you have placed a TButton, a TEdit and a TMemo on a form.

Code

var
  Form1: TForm1;
  mycoll: TMatchCollection;
  myenum: TMatchCollectionEnumerator;

implementation

{$R *.dfm}

// Creates and lists the match collection, the matches in that
// collection and the groups in those matches.
procedure TForm1.Button1Click(Sender: TObject);
const
  bigString = 'Look for a the strings in this strang of strungs.';
  littlestring = '(str)([iau]ng)';
var
  regex: TRegEx;
  i, j: integer;
  mygrps: TGroupCollection;
begin
  regex:= TRegEx.Create(littlestring);
  mycoll:= regex.Matches(bigString);
  Edit1.Text:= 'Count: ' + IntToStr(mycoll.Count);
  memo1.Lines.Add('First Collection: ');
  for i := 0 to mycoll.Count-1 do
  begin
    memo1.Lines.Add('Match #' + IntToStr(i) + ': ' + mycoll.Item[i].Value);
    memo1.Lines.Add('Group: ' + IntToStr(i));
    mygrps:= mycoll.Item[i].Groups;
    for j := 0 to mygrps.Count-1 do
      memo1.Lines.Add('Value: ' + mygrps.Item[j].Value);
  end;

end;

// Moves the enumerator to the next member of the collection.
// Create the match collection and set the enumerator first.
// MoveNext only moves to the last, does not wrap to the first.
procedure TForm1.Button2Click(Sender: TObject);
begin
  myenum.MoveNext;
end;

// Sets the enumerator in the current match collection.
procedure TForm1.Button3Click(Sender: TObject);
begin
  myenum:= mycoll.GetEnumerator;
end;

// Create a different match collection.
//Note that MoveNext and Current work on the old match collection
// until the enumerator is set.
procedure TForm1.Button4Click(Sender: TObject);
const
  bigString = 'Look for a the strings.';
  littlestring = 'str[iau]ng';
var
  regex: TRegEx;
  i: integer;
begin
  regex:= TRegEx.Create(littlestring);
  mycoll:= regex.Matches(bigString);
  Edit1.Text:= 'Count: ' + IntToStr(mycoll.Count);
  for i := 0 to mycoll.Count-1 do
    memo1.Lines.Add('Second collection: ' + mycoll.Item[i].Value);
end;

// Displays the current match of the collection.
// Current does not work unit the match collection is created,
// the enumeration is set and MoveNext sets the index to the first member.
procedure TForm1.Button5Click(Sender: TObject);
begin
  memo1.Lines.Add('Enum current: ' + myenum.Current.Value);
end;

Uses