TRegExReplace (C++)

From RAD Studio Code Examples
Jump to: navigation, search


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'.


/* 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;
	TEdit *Edit2;
	void __fastcall Button1Click(TObject *Sender);
private:	// User declarations
public:		// User declarations
	__fastcall TForm1(TComponent* Owner);
	System::UnicodeString __fastcall TForm1::ReplaceCC(const TMatch &Match);

System::UnicodeString __fastcall TForm1::ReplaceCC(const TMatch &Match)
  i = i + 1;
  return IntToStr(i);

void __fastcall TForm1::Button1Click(TObject *Sender)
  const System::UnicodeString input = Edit1->Text;
  TRegEx *regex = new TRegEx("cc");
  TMatchEvaluator myEval = &ReplaceCC;
  i = 0;
  Edit2->Text = regex->Replace(input, myEval);


See Also