TRegExReplace (C++)

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 regular expression. This TMatchEvaluator will replace each occurrence 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

/* ReplaceCC is used here as a TMatchEvaluator, which is a closure in C++.
   So ReplaceCC has to be a member of a class.
*/
class TForm1 : public TForm
{
__published:	// IDE-managed Components
    TButton *Button1;
    TEdit *Edit1;
    TMemo *Memo1;
    TEdit *Edit2;
    void __fastcall Button1Click(TObject *Sender);
private:	// User declarations
    int32_t i;
    String __fastcall ReplaceCC(const TMatch &Match);
public:		// User declarations
    __fastcall TForm1(TComponent* Owner);
};

String __fastcall TForm1::ReplaceCC(const TMatch &Match)
{
  i = i + 1;
  return IntToStr(i);
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  i = 0;
  String input = Edit1->Text;
  TRegEx regex("cc", TRegExOptions() << TRegExOption::roNotEmpty);
  TMatchEvaluator myEval = &(ReplaceCC);
  Edit2->Text = regex.Replace(input, myEval);
}

Uses

See Also