TRegExReplace (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example uses the TRegEx TMatchEvaluator in a Replace method to implement a complex replacement. Place a TButton and two TEdits on the form. Make a TRegEx variable in the ButtonClick routine and call the TRegEx constructor to initialize its data structures and assign its regex. This TMatchEvaluator will replace each occurence of 'cc' with the number of times it is found in the string. If the input string is: 'aabbccddeeffcccgghhcccciijjcccckkcc' the final result should be: 'aabb1ddeeff2cgghh34iijj56kk7'.

Code

function TForm1.ReplaceCC(const Match: TMatch): string;
begin
  i := i + 1;
  Result := InttoStr(i);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  regex: TRegEx;
  input: string;
  myEval: TMatchEvaluator;
begin
  i := 0;
  input := Edit1.Text;
  regex.Create('cc');
  myEval := ReplaceCC;
  Edit2.Text := regex.Replace(input, myEval);
end;

Uses

See Also