Using Regular Expression on C++Builder FireMonkey Application
Here another C++ example showing how to use the RTL regular expression on C++Builder FireMonkey Application.
This example validate a string content based on four different regular expression, which are:
- Checks if the given text is a validate e-mail address
- Checks if the given text contains a valid IP address
- Checks if the given text is a valid date (dd-mm-yyyy)
- Checks if the given text is a valid date (mm-dd-yyyy)
The follow code shows the four regular expressions used by this application.
void __fastcall TForm1::lbRegExpChange(TObject *Sender) { switch (lbRegExp->ItemIndex) { case 0: lbType->Text = "E-mail for validation"; MemoRegEx->Text = "^((?>[a-zA-Z\d!#$%&''*+\\-/=?^_`{|}~]+\\x20*" "|\"((?=[\\x01-\\x7f])[^\"\\\\]|\\\\[\\x01-\\x7f])*\"\\" "x20*)*(?\.?[a-zA-Z\d!" "#$%&''*+\\-/=?^_`{|}~]+)+|\"\"((?=[\\x01-\\x7f])" "[^\"\\\\]|\\\\[\\x01-\\x7f])*\")@(((?!-)[a-zA-Z\\d\\" "-]+(?)$"; break; case 1: { // Accept IP address between 0..255 lbType->Text = "IP address for validation (0..255)"; MemoRegEx->Text = "\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\" ".(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"; break; } case 2: { // Data interval format mm-dd-yyyy lbType->Text = "Date in mm-dd-yyyy format from between 01-01-1900 and 12-31-2099"; MemoRegEx->Text = "^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[" "01])[- /.](19|20)\\d\\d$"; break; } case 3: { // Data interval format mm-dd-yyyy lbType->Text = "Date in dd-mm-yyyy format from between 01-01-1900 and 31-12-2099"; MemoRegEx->Text = "^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[01" "2])[- /.](19|20)\\d\\d$"; break; } } EditTextChangeTracking(EditText); }
To execute the validation you can use the method TRegExp::IsMatch as you can see bellow:
void __fastcall TForm1::EditTextChangeTracking(TObject *Sender) { // EditText contain the string value and MemoRegEx the regular expression if (TRegEx::IsMatch(EditText->Text, MemoRegEx->Text)) { SEResult->ShadowColor = TAlphaColors::Green; } else SEResult->ShadowColor = TAlphaColors::Red; }
Since this is a FireMonkey Application, I used a Shadow Effect to show if the Edit box value is valid or not (Green=valid / Red=invalid). The following image shows what happen when you input a invalid e-mail address on Windows and Mac.
Now the results when you provide the correct e-mail address.
You can download the source code from here or just update your local RAD Studio XE2 samples folder from our RAD Studio SVN repository.
Leave a Reply
Want to join the discussion?Feel free to contribute!