Reputation: 694
I want to extract SAAM
and SAAMI
from the following text by using RegEX
(I'm coding in Delphi XE4 and XE5) :
RegEx = 'Name:\s?(.*),Family:\s?(.*)';
For example I've this text :
Name: SAAM
Family: SAAMI
I wrote this code, and use the MatchAgain
method of TPerlRegEx
for matching two regex ('Name:\s?(.*)'
And 'Family:\s?(.*)'
) .
...
var
RX: TPerlRegEx;
const
RegEx = 'Name:\s?(.*),Family:\s?(.*)';
begin
RX := TPerlRegEx.Create;
try
RX.RegEx := RegEx;
RX.Subject := mmo1.Text;// The mmo1.text value is "Name: SAAM and Family: SAAMI"
if RX.Match then
begin
repeat
ShowMessage('Name is :' + RX.Groups[1]);
ShowMessage('Family is :' + RX.Groups[2]);
until not RX.MatchAgain;
end;
finally
RX.Free;
end;
...
Why this code doesn't works ??
Upvotes: 0
Views: 318
Reputation: 694
I change my code to this, and it works (Almost :-) ) correctly for me.
Example text :
Junk text :-)
Junk text :-)
Junk text :-)
Name: SAAM
Junk text :-)
Junk text :-)
Junk text :-)
Junk text :-)
Junk text :-)
Family: SAAMI
Junk text :-)
Junk text :-)
Junk text :-)
New code :
var
RX: TPerlRegEx;
i: Integer;
const
RegEx = 'Name:\s?(.*)|Family:\s?(.*)';
begin
i := 1;
RX := TPerlRegEx.Create;
try
RX.RegEx := RegEx;
RX.Subject := mmo1.Text;
if RX.Match then
begin
repeat
case i of
1:
ShowMessage('Name is: ' + RX.Groups[i]);
2:
ShowMessage('Family is: ' + RX.Groups[i]);
end;
Inc(i);
until not RX.MatchAgain;
end;
finally
RX.Free;
end;
And result :
Name is: SAAM
Family is: SAAMI
Upvotes: 3