简体   繁体   中英

Why MatchAgain method of TPerlRegEx doesn't works

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 ??

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM