Source Code Checking email syntax using TRegEx - Regular Expressions class

emailx45

Social Engineer
Joined
May 5, 2008
Messages
2,387
Reaction score
2,149
My sample to "check emailx syntax" using TRegEx - Regular Expressions class
View attachment 1190


[SHOWTOGROUPS=4,20]
Code:
uses
  System.RegularExpressions;

function CheckEmailAdress(const EmailAddress: string): Boolean;
const
  EMAIL_REGEX = '^((?>[a-zA-Z\d!#$%&''*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])' + '[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)' + { }
    '(?>\.?[a-zA-Z\d!#$%&''*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]' +       { }
    '{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$';
begin
  Result := TRegEx.IsMatch(EmailAddress, EMAIL_REGEX);
end;

procedure TForm1.btnCheckEmailSyntaxClick(Sender: TObject);
var
  lEmailListArrayString: TArray<string>;
  lTextWithEmail       : string;
begin
  lEmailListArrayString := nil;
  //
  lTextWithEmail := '[email protected];email@provider;[email protected];'; // the "last" will be "blank"
  //
  Memo1.Lines.Clear;
  //
  lEmailListArrayString := lTextWithEmail.Split([';'], TStringSplitOptions.ExcludeEmpty);
  //
  Memo1.Lines.Add(StringOfChar('-', 40));
  Memo1.Lines.AddStrings(lEmailListArrayString);
  Memo1.Lines.Add('Emails counting = ' + Length(lEmailListArrayString).ToString);
  Memo1.Lines.Add(StringOfChar('-', 40));
  //
  lTextWithEmail := '';
  //
  for lTextWithEmail in lEmailListArrayString do
  begin
    if { (lTextWithEmail.Trim <> '') and } CheckEmailAdress(lTextWithEmail) then
      Memo1.Lines.Add('--> ' + lTextWithEmail + ', email syntax OK')
    else
      Memo1.Lines.Add('--> ' + lTextWithEmail + ', email syntax DONT OK');
  end;
end;

[/SHOWTOGROUPS]
 

techn1

New member
Joined
Jul 31, 2008
Messages
1
Reaction score
0
"Yo, been there, done that. Used TRegEx for parsing some complex email formats in a Delphi project and it saved me a ton of headaches. Just remember to escape those special chars or you'll get errors like crazy"
 

Lihach666

New member
Joined
Nov 18, 2017
Messages
4
Reaction score
0
Yeah, TRegEx is definitely a solid choice for regex in Delphi. I've used it in the past and it's worked great for parsing email addresses and validating input formats. One thing to keep in mind is that it's a bit more verbose than some of the newer regex libraries out there, but it gets the job done.
 
Top