我想提取Thunderbird电子邮件文件中找到的所有电子邮件地址.有时,电子邮件会在空格中包含,有时以<>和其他方式.我能够在每个字符串上找到@出现的位置,但是如何在形成电子邮件之前和之后抓取字符?
谢谢.
正则表达式诞生于此类工作.这是一个最小的控制台应用程序,它显示了如何使用RegEx从一个长文本块中提取所有电子邮件地址:
program Project25;
{$APPTYPE CONSOLE}
uses
SysUtils, PerlRegex;
var PR: TPerlRegEx;
TestString: string;
begin
// Initialize a test string to include some email addresses. This would normally
// be your eMail text.
TestString := '<one@server.domain.xy>, another@otherserver.xyz';
PR := TPerlRegEx.Create;
try
PR.RegEx := '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b'; // <-- this is the actual regex used.
PR.Options := PR.Options + [preCaseLess];
PR.Compile;
PR.Subject := TestString; // <-- tell the TPerlRegEx where to look for matches
if PR.Match then
begin
// At this point the first matched eMail address is already in MatchedText, we should grab it
WriteLn(PR.MatchedText); // Extract first address (one@server.domain.xy)
// Let the regex engine look for more matches in a loop:
while PR.MatchAgain do
WriteLn(PR.MatchedText); // Extract subsequent addresses (another@otherserver.xyz)
end;
finally PR.Free;
end;
Readln;
end.
Run Code Online (Sandbox Code Playgroud)
请参阅此处了解如何获取旧版本的Delphi的正则表达式:http: //www.regular-expressions.info/delphi.html