为什么TPerlRegEx的MatchAgain方法不起作用

时间:2013-11-06 09:29:55

标签: regex delphi

我想使用SAAM(我在Delphi XE4和XE5中编码)从以下文本中提取SAAMIRegEX

RegEx = 'Name:\s?(.*),Family:\s?(.*)';

例如,我有这样的文字:

Name: SAAM
Family: SAAMI

我编写了此代码,并使用MatchAgain TPerlRegEx方法匹配两个正则表达式('Name:\s?(.*)''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;
...

为什么这段代码不起作用?

1 个答案:

答案 0 :(得分:3)

我将我的代码更改为此代码,它对我来说正常工作(几乎:-))。

示例文字:

  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 :-)

新代码:

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;

结果:

Name is: SAAM
Family is: SAAMI